1.首先在自定义的模型.m文件中加上存储和读取的解析,分别是:
- (void)encodeWithCoder:(NSCoder*)aCoder{
[aCoder encodeObject:self.title forKey:@"title"];
[aCoder encodeInt:self.rowheight forKey:@"rowheight"];
}
- (instancetype)initWithCoder:(NSCoder*)aDecoder{
if([super init]) {
self.title= [aDecoder decodeObjectForKey:@"title"];
self.rowheight= [aDecoder decodeIntForKey:@"rowheight"];
}
return self;
}
2.然后开始存储模型数组
NSMutableArray *array = [ NSMutableArray array ];
for(inti =0;i <self.dateArray.count; i++ ) {
NewsModel*model =self.dateArray[i]; //取出每个模型
NSData*data = [NSKeyedArchiver archivedDataWithRootObject:model ];//将每个模型转成NSData类型
[array addObject:data];//将NSData加入临时可变数组中
}
NSArray* mutableArray = [NSArray arrayWithArray:array];//将临时可变数组转化为不可变数组
[[NSUserDefaults standardUserDefaults] setObject:mutableArray forKey:@"xxxxx"];//进行存储
3.取值
NSArray*arr = [[NSUserDefaults standardUserDefaults] objectForKey:@"xxxxx"];//取出存储data的数组
NSMutableArray*mustablearr = [NSMutableArray array];//生成可变数组,用来存储我们所要取的值
for(inti =0; i < arr.count; i++) {
NewsModel*model = [NSKeyedUnarchiver unarchiveObjectWithData:arr[i]];//将每个data转化为自定义的模型
[ mustablearr addObject:model ];//将模型加入可变数组
}