关于 writeToFile 读写文件:当字典中键值对以 Model(例如:studentModel)为值时发现 Dictionary 调用 writeToFile 方法无法生成 plist 文件,经过多次测试发现, 调用 writeToFile 方法时 Dictionary 中不能包含 model 对象,针对这一现象,对 model 数据进行处理转化为 Dictionary ,就可以存储为 plist 文件.当读取 plist 文件时再将 Dictionary 转化为 Model.
下面是以 studentModel 为例实现代码:
studentModel 包含三个属性:name,passWord,sex
1 @PRoperty (nonatomic , copy)NSString *name;2 @property (nonatomic , copy)NSString *passWord;3 @property (nonatomic , copy)NSString *sex;
为studentModel 添加以实例方法,完成将 Model 对象转为 Dictionary
1 - (NSMutableDictionary *)changeModelToDic{2 NSMutableDictionary *dic = [[NSMutableDictionary alloc]init];3 [dic setObject:self.name forKey:@"name"];4 [dic setObject:self.passWord forKey:@"passWord"];5 [dic setObject:self.sex forKey:@"sex"];6 return dic;7 }
为studentModel 添加类方法.完成将 Dictionary 转化为 Model 对象
1 + (Student*)changDicToStudent:(NSMutableDictionary *)dic{2 Student *stu = [[Student alloc]init];3 stu.name = [dic objectForKey:@"name"];4 stu.passWord = [dic objectForKey:@"passWord"];5 stu.sex = [dic objectForKey:@"sex"];6 return stu;7 }
新闻热点
疑难解答