最近一直做本地存儲的問題位他,是寫入到j(luò)son文件中,使用的時候在讀取部服,不過如果數(shù)組中存儲的是模型數(shù)據(jù)唆姐,這樣可能會造成存儲或者讀取失敗,在儲存數(shù)組前廓八,記得先遍歷數(shù)組奉芦,然后模型轉(zhuǎn)字典,再把字典存儲到數(shù)組中剧蹂,這樣就OK了声功,下面我的代碼是數(shù)組中存的字典,無需在轉(zhuǎn)換了宠叼。
不過使用writeToFile寫入文件的時候先巴,本次保存會把上次保存的數(shù)據(jù)給覆蓋掉,不能累加,解決方法筹裕,可以使用歸檔存儲醋闭,也可以換中思路,再次保存的時候朝卒,先讀取上次保存的數(shù)據(jù)证逻,然后一起寫入這樣就OK了。
在適當(dāng)?shù)臅r候調(diào)用就可以了
保存
[self saveArrayandNSArray:self.dataDic andByAppendingPath:@"未盤.json"];
讀取
NSMutableArray *weipan = [self readArrayByAppendingPath:@"未盤.json"];
刪除
[self removeNSArrayByAppendingPaht:@"未盤.json"];
#pragma mark - 讀取本地數(shù)組
- (NSMutableArray *)readArrayByAppendingPath:(NSString *)arrayName{
// 拼接路徑
NSString * docDir = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask,YES) lastObject];
NSString * fileName = [docDir stringByAppendingPathComponent:arrayName];
NSData *jdata = [[NSData alloc] initWithContentsOfFile:fileName];
if (jdata) {
//反序列化
NSArray *array = [NSJSONSerialization JSONObjectWithData:jdata options:0 error:NULL];
NSMutableArray *arrayDict=[NSMutableArray array];
for (int i=0; i<array.count; i++) {
NSDictionary *dict=array[i];
[arrayDict addObject:dict];
}
return arrayDict;
}else {
NSLog(@"沒有數(shù)據(jù)抗斤。囚企。。");
return nil;
}
}
#pragma mark - 保存本地數(shù)組
- (void)saveArrayandNSArray:(NSMutableArray *)array andByAppendingPath:(NSString *)name {
//創(chuàng)建json文件 獲取根目錄
NSString * docDir = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask,YES) lastObject];
NSString * fileName = [docDir stringByAppendingPathComponent:name];
if (array) {
//字典轉(zhuǎn)二進制
NSData *dicData = [NSJSONSerialization dataWithJSONObject:array options:NSJSONWritingPrettyPrinted error:nil];
//二進制轉(zhuǎn)字符串
NSString *dataStr = [[NSString alloc] initWithData:dicData encoding:NSUTF8StringEncoding];
[dataStr writeToFile:fileName atomically:YES encoding:NSUTF8StringEncoding error:nil];
}
}
#pragma mark - 刪除本地數(shù)組
- (void)removeNSArrayByAppendingPaht:(NSString *)arrayName {
NSString *docDir = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask,YES) lastObject];
NSString * fileName = [docDir stringByAppendingPathComponent:arrayName];
NSFileManager *manager=[NSFileManager defaultManager];
[manager removeItemAtPath:fileName error:nil];
}