之前试了很长时间,将数组直接写入本地,根本写不进去,后来看到一位大神写的,我试了试,真的可以存
#define KdirectoryName @"EventListData"
#define KfileName @"EventList.plist"
1.初始化路径
-(NSString*)filePath{
//1.1获取文件管理器对象
NSFileManager *manager=[NSFileManager defaultManager];
//1.2合并文件夹路径
NSString *documentsPath=NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)[0];
NSString*directoryPath=[documentsPathstringByAppendingPathComponent:KdirectoryName];
if (![manager createDirectoryAtPath:directoryPath withIntermediateDirectories:YES attributes:nil error:nil]) {
NSLog(@"=====文件夹创建失败");
returnnil;
}
//2.创建文件路径
_filePath=[directoryPath stringByAppendingPathComponent:KfileName];
return _filePath;
}
2.将数据存到本地
我这边是先从本地读取,然后加载的,就会导致数据重复,所以加个判断,防止,同时从本地读取和网络加载导致数据重复
NSMutableArray *idArr = [NSMutableArray array];
for(HDEventModal*model in self.dataArr) {
[idArr addObject:model.ID];
}
NSMutableArray *arr2 = [NSMutableArray array];
for(HDEventModal*modelinobjArr) {
if(model.ID&& model.ID.length>0 && ![idArr containsObject:model.ID]) {
[arr2addObject:model];
}
}
[self.dataArraddObjectsFromArray:arr2];
在网络请求的方法里, 将模型数组里的模型再转换成字典,将装有字典的数组存到本地,事实上也就是以请求下来的json格式存到本地
NSMutableArray*mutArr = [NSMutableArray array];
for(int i =0; i<self.dataArr.count ; i++){
HDEventModal*model =self.dataArr[i];
NSDictionary*dic = model.mj_keyValues;
[mutArr addObject:dic];
}
[mutArr writeToFile:self.filePath atomically:YES];
3.读取本地数据
将数据从本地取出,再转化成模型,self.dataArr就是数据源
NSArray *arr =[NSArray arrayWithContentsOfFile:self.filePath];
self.dataArr = [HDEventModal mj_objectArrayWithKeyValuesArray:arr];
网友评论