A,歸檔解檔(多針對於模型或者數組,利用MJExtension)
1,先在model里的.m文件寫上MJCodingImplementation
2,再進行模型歸檔:
#define APP_DOCUMENT [NSSearchPathForDirectoriesInDomains (NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0]
#define DocumentPath(path) [APP_DOCUMENT stringByAppendingPathComponent:path]
[NSKeyedArchiver archiveRootObject:模型或者數組 toFile:DocumentPath(@"freeOrderSelectedCar")];
3,解檔
NSString *file = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES).firstObject stringByAppendingPathComponent:@"freeOrderSelectedCar"];
模型或者數組 = [NSKeyedUnarchiver unarchiveObjectWithFile:file];
/* 實現下面的方法,說明哪些屬性不需要歸檔和解檔 */
+ (NSArray *)mj_ignoredCodingPropertyNames{
return @[@"name"];
}
B,保存數組或字典到本地(json數據的,如果是模型,則用上面的歸檔)
1, 字典轉成二進制數據存到本地
NSData *resultData = [NSJSONSerialization dataWithJSONObject:字典或數組 options:NSJSONWritingPrettyPrinted error:nil];
[resultData writeToFile:DocumentPath(@"areas.plist") atomically:YES];
2, 讀取本地數據
NSData *data = [NSData dataWithContentsOfFile:DocumentPath(@"areas.plist")];
//需要判斷數據為nil情況,因為如果為nil則無法轉成字典的
if (!isEmpty(data)) {
NSDictionary * resultDic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];或
NSArray * resultArray = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
}
C,偏好設置(保存輕量級的數據)
//從沙盒里面讀取鍵“key”對應的內容“值”
[[NSUserDefaults standardUserDefaults] objectForKey:<#key#>];
//把內容"value"存入到沙盒,對應的鍵是“key”
[[NSUserDefaults standardUserDefaults] setObject:<#value#> forKey:<#key#>];
//同步到沙盒;必須要寫,不寫會產生不可預測的Bug
[[NSUserDefaults standardUserDefaults] synchronize];
D,鏈表(針對數據量大,且為Json格式)(如果數據十分重要不容缺失則最好采用鏈表存儲)(采用STDBManager庫,如果找不到這個庫,可以留下聯系方式。后面我會放到github上面)
1,初始化數據庫鏈表
- (instancetype)init
{
self = [super init];
if (self) {
// 創建緩存數據庫表
[[STDatabaseManager sharedInstance] createTableWithName:TABLE_CACHE];
}
return self;
}
2,存儲數據到鏈表(把json格式的數據存入的)
if (!isEmpty(json)) {
[[STDatabaseManager sharedInstance] putJsonObject:json withId:@“Key” intoTable:TABLE_CACHE];
}
3,讀取數據(如果需要模型或模型數組,可以拿到的json數據轉為模型或模型數組)
NSObject* data = [[STDatabaseManager sharedInstance] getJsonObjectById:@“Key” fromTable:TABLE_CACHE];