程序运行效果截图:
1,数据的共享可以通过AppDelegate来解决
因为AppDelegate的特殊作用,它可以在其他视图控制器中获取AppDelegate对象,因此,将数据模型放置到AppDelegate类中,所有的页面都相它获取数据,并且共同维护它(CRUD操作),如此就可以实现数据共享。
例如原型视图控制器中的loadAllContractor方法可以修改如下:
-(void)loadAllContractor{
//获取当前应用指针,访问所有联系人集合
AppDelegate*appDelegate = (AppDelegate*)[UIApplicationsharedApplication].delegate;
self.allContactorsArray= appDelegate.allContactorsArray;
}
2、数据的持久化
持久化方式很多,数据库这里先不提,而是选用简单的plist文件来解决
步骤:
1)修改MPContactor类,实现NSCoding协议,让其支持归档。
这里注意,处理归档相关操作,还新增了两个成员属性:favorite和portraitFileName
@property(nonatomic,assign)BOOLfavorite;
@property(nonatomic,retain)NSString*portraitFileName;
-(id)initWithName:(NSString*)name andPortraitFileName:(NSString*)fileName andIntroduce:(NSString*)introduce;
//加载plist文件,读取联系人信息,如果不存在则创建
if([selfloadAllContactorFromPlistFile] ==NO) {
[selfinitAndSaveAllContactorsToPlistFile];
}
//程序运行,从plist文件中加载数据,如果成功返回YES,如果文件不存在则返回NO
-(BOOL)loadAllContactorFromPlistFile{
NSString*filePath =NSHomeDirectory();
NSString*filePath =NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask,YES)[0];
NSLog(@"%@",filePath);
self.allContactorsArray= [NSKeyedUnarchiverunarchiveObjectWithFile:filePath];
if(self.allContactorsArray!=nil) {
returnYES;
}
returnNO;
}
//首次读取需要创建并初始化plist文件,主要步骤如下
//1、创建字典集合,初始化数据
//2、将当前数据写入plist文件
-(void) initAndSaveAllContactorsToPlistFile{
MPContactor*liwen = [[MPContactoralloc]initWithName:@"李玟"andPortraitFileName:@"liwen.png"andIntroduce:@"国际范儿的歌手,大气、努力、态度诚恳!"];
MPContactor*likeqin = [[MPContactoralloc]initWithName:@"李克勤"andPortraitFileName:@"likeqin.png"andIntroduce:@"唱功厉害,态度认真"];
MPContactor*xujiaying = [[MPContactoralloc]initWithName:@"徐佳莹"andPortraitFileName:@"xujiaying.png"andIntroduce:@"国际范儿的歌手,大气、努力、态度诚恳!"];
MPContactor*zhangxinzhe = [[MPContactoralloc]initWithName:@"张信哲"andPortraitFileName:@"zhangxinzhe.png"andIntroduce:@"姜是老的辣"];
MPContactor*rongzuer = [[MPContactoralloc]initWithName:@"容祖儿"andPortraitFileName:@"rongzuer.png"andIntroduce:@"性格不错,明明可以靠脸,但是..."];
MPContactor*laolang = [[MPContactoralloc]initWithName:@"老狼"andPortraitFileName:@"laolang.png"andIntroduce:@"时代的标志性人物,悲催的是没来及找到感觉就..."];
MPContactor*suyunying = [[MPContactoralloc]initWithName:@"苏运莹"andPortraitFileName:@"suyunying.png"andIntroduce:@"有特点的丫头,确实够野!"];
MPContactor*huangzhilie = [[MPContactoralloc]initWithName:@"黄致列"andPortraitFileName:@"huangzhilie.png"andIntroduce:@"有实力,但是比较明显的工业特征,还是厉害的。"];
liwen.favorite=YES;
rongzuer.favorite=YES;
xujiaying.favorite=YES;
self.allContactorsArray= [NSMutableArrayarrayWithObjects:liwen,likeqin,xujiaying,zhangxinzhe,rongzuer,laolang,suyunying,huangzhilie,nil];
[selfsaveAllContactorsDataToPlistFile];
}
3)修改个页面的数据源初始化代码:
-(void)loadAllContractor{
//获取当前应用指针,访问所有联系人集合
AppDelegate*appDelegate = (AppDelegate*)[UIApplicationsharedApplication].delegate;
self.allContactorsArray= appDelegate.allContactorsArray;
}
网友评论