iOS 使用 NSUserDefaults 存储自定义对象
2017-04-19 本文已影响812人
huangxiongbiao
原理:将自定义对象归档成data后,利用NSUserDefaults写入本地
一、保存对象
1、归档对象
需要实现NSCoding协议,参考http://www.jianshu.com/p/02da153d3583 继承Model类即可
//首先,要建立一个集成Model对象或者实现NSCoding协议的对象
Student *student = [[Student alloc] init];
//下面进行的是对student对象的 name , studentNumber ,sex 的赋值
student.name = @"刘德华";
student.studentNumber = @"2313213";
student.sex = @"男";
NSData *data = [NSKeyedArchiver archivedDataWithRootObject:student];
2、将对象写入本地
利用NSUserDefaults或者封装的HXBSaveTool类(http://www.jianshu.com/p/ac273e44bd7c 代码解释)
方法1== NSUserDefaults
NSUserDefaults *user = [NSUserDefaults standardUserDefaults];
[user setObject:data forKey:@"oneStudent"];
//同步到本地
[user synchronize];
方法2== HXBSaveTool分装类
[HXBSaveTool setObject:data forKey:@"oneStudent"];
二、取出对象
1、取出本地保存的data
利用NSUserDefaults或者封装的HXBSaveTool类(http://www.jianshu.com/p/ac273e44bd7c 代码解释)
方法1== NSUserDefaults
NSUserDefaults *user = [NSUserDefaults standardUserDefaults];
NSData *data = [user objectForKey:@"oneStudent"];
方法2== HXBSaveTool分装类
NSData *data = [HXBSaveTool objecForKey:@"oneStudent"];
2、将data解档为对象
Student *student = [NSKeyedUnarchiver unarchiveObjectWithData:data];
三、保存数组自定义对象
如果要保存对象数组到到本地
对象实现NSCoding协议,代码如下:
存数组对象
//存储信息
NSData *data = [HXBSaveTool valueForKey:kRecorde];
NSMutableArray *dataArr;
if (data) {
dataArr = [NSKeyedUnarchiver unarchiveObjectWithData:data];
}else{
dataArr = [NSMutableArray array];
}
OpenRecordeModel *recorde = [OpenRecordeModel new];
recorde.pid = model.pid;
recorde.tel = [HXBSaveTool valueForKey:kUserPhone];
recorde.crjldate = [formatter stringFromDate:[NSDate date]];
[dataArr addObject:recorde];
[HXBSaveTool setValue:[NSKeyedArchiver archivedDataWithRootObject:dataArr] forKey:kRecorde];
取数组对象
_dataArr = [NSKeyedUnarchiver unarchiveObjectWithData:[HXBSaveTool valueForKey:kRecorde]];