iOS開發(fā)常用的數(shù)據(jù)持久化方式有NSUserdefaults(屬性列表)番枚,NSKeyedArchiver(歸檔/解歸檔)鲫竞,write , SQLite 3溢十, CoreData等袱巨。
1.【屬性列表】
NSUserDefaults 是一個(gè)單例适篙,整個(gè)程序中只有一個(gè)實(shí)例對(duì)象,用于數(shù)據(jù)的永久保存蜂奸,也是使用最簡(jiǎn)單犁苏。
??支持的數(shù)據(jù)類型有:NSNumber,double窝撵,float傀顾,NSInteger襟铭,NSString碌奉,NSDate,NSArray寒砖,BOOL赐劣,NSDictionary。
??NSUserdefaults存儲(chǔ)的對(duì)象是不可變的哩都,如果想要存一個(gè)可變數(shù)組的對(duì)象魁兼,要先將它轉(zhuǎn)為不可變數(shù)組,然后存到NSUserdefaluts中漠嵌。
?? NSUserdefaults本身不支持自定義對(duì)象存儲(chǔ)咐汞,不過(guò)它支持NSData
//保存不可變數(shù)據(jù)
NSString *obj = @"obj";
[[NSUserDefaults standardUserDefaults] setObject:obj forKey:@"objkey"];
//讀取不可變數(shù)據(jù)
NSString *obj = [[NSUserDefaults standardUserDefaults] objectForKey:@"objkey"]
//保存可變數(shù)據(jù)
NSMutableArray *array = [[NSMutableArray alloc]initWithObjects:@"A",@"B",@"C", nil];
[array addObject:@"D"];
[[NSUserDefaults standardUserDefaults] setObject:array forKey:@"arraykey"];
//讀取可變數(shù)據(jù)(不能直接讀取)
NSArray *array= [[NSUserDefaults standardUserDefaults] ObjectForKey:array forKey:@"arraykey"];
NSMutableArray *arr = [[NSMutableArray alloc]initWithArray:array];
//保存對(duì)象
Dog *dog = [Dog alloc]init]; //自定義一個(gè)Dog類,并實(shí)例化一個(gè)對(duì)象dog
dog.xxx = ……//屬性
NSData *data = [NSKeyedArchiver archivedDataWithRootObject:dog]; //NSUserDefaults不支持自定義對(duì)象儒鹿,但支持NSData化撕,所以將自定義對(duì)象轉(zhuǎn)化成NSData類型
[[NSUserDefaults standardUserDefaults] setObject:data forKey:@"dog"];
//對(duì)象讀取
NSData *data = [[NSUserDefaults standardUserDefaults] objectForKey:@"student"];
Dog *dog = [NSKeyedUnarchiver unarchiveObjectWithData:data];
??保存不同的數(shù)據(jù),key不能重復(fù)约炎,不然會(huì)被覆蓋或者bug
【歸檔/解歸檔】
歸檔/解歸檔是將對(duì)象以穩(wěn)健的形式保存到磁盤中(也稱序列化植阴,持久化)蟹瘾,使用時(shí)通過(guò)保存該文件的路徑來(lái)讀取該文件內(nèi)容(解檔,反序列)掠手。
??用于foundation中對(duì)象的存取
??自定義對(duì)象的存取
//歸檔
NSMutableDictionary *dict = [NSMutableDictionary dictionary];
[dict setObject:@"A" forKey:@"a"];
BOOL ret = [NSKeyedArchiver archiveRootObject:dict toFile:@"xxx.xx.x保存路徑"];
if (ret){
NSLog(@"歸檔成功");
}else {
NSLog(@"歸檔失敗");
}
//解歸檔
id obj = [NSKeyedUnarchiver unarchiveObjectWithFile:@"xxx.xx.x保存路徑"];
if ([obj isKindOfClass:[NSDictionary class]]){
NSMutableDictionary *dict = obj;
}
【write寫入】
1.】拼接生成該目錄下的文件
NSString * documentDirectory = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask,YES) firstObject];
NSString * docFile =[documentDirectory stringByAppendingPathComponent:fileName];
2.】往文件寫入數(shù)據(jù)
2.1】NSData寫入文件
[data writeToFile:FileName atomically:YES];
2.2】NSString 寫入文件
NSError *error = nil;
[string writeToFile:docFile atomically:YES encoding:NSUTF8StringEncoding error:&error];
if (error) {
NSLog(@"寫入文件失敽镀印:error = %@",error);
}else{
NSLog(@"寫入文件成功");
}
2.3】NSDictionary同上類似。
3.】從文件中讀取
NSData *data = [NSData dataWithContentsOfFile: docFile];
NSString *string = [NSString stringWithContentsOfFile:docFile encoding:NSUTF8StringEncoding error:nil];