IOS提供的數據持久化方式有:SQLite、CoreData、屬性列表、NSUserDefault、對象歸檔。
這里來簡單介紹下對象歸檔:
對象歸檔是將對象歸檔以文件的形式保存到磁盤中(也稱為序列化,持久化),使用的時候讀取該文件的保存路徑讀取文件的內容(也稱為接檔,反序列化),
(對象歸檔的文件是保密的,在磁盤上無法查看文件中的內容,而屬性列表是明文的,可以查看)。
對象歸檔有兩種方式:1:對foundation中對象進行歸檔 2:自定義對象歸檔
1、簡單對象歸檔
使用兩個類:NSKeyedArichiver、NSKeyedUnarchiver
NSString *homeDirectory = NSHomeDirectory(); //獲取根目錄
NSString homePath = [homeDirectory stringByAppendingPathComponent:@"自定義文件名,如test.archiver"];
NSArray *array = @[@"abc", @"123", @12];
Bool flag = [NSKeyedArichiver archiveRootObject:array toFile:homePath];
if(flag) {
NSLog(@"歸檔成功!");
}
讀取歸檔文件的內容:
NSArray *array = [NSKeyedUnarchiver unarchiveObjectWithFile: homePath ];
NSLog(@"%@", array);
這樣就簡單了實現了將NSArray對象的歸檔和解檔。
但是這種歸檔方式有個缺點,就是一個文件只能保存一個對象,如果有多個對象要保存的話那豈不是有n多個文件,這樣不是很適合的,所以有了下面這種歸檔方式。
2、自定義內容歸檔
歸檔:
使用NSData實例作為歸檔的存儲數據
添加歸檔的內容---使用鍵值對
完成歸檔
解歸檔:
從磁盤讀取文件,生成NSData實例
根據NSData實例和初始化解歸檔實例
解歸檔,根據key訪問value
NSString *homeDirectory = NSHomeDirectory(); //獲取根目錄
NSString homePath = [homeDirectory stringByAppendingPathComponent:@"自定義文件名,如test.archiver"];
NSMutableData *data = [[NSMutableData alloc] init];
NSKeyedArchiver *archiver = [[NSKeyedArchiver alloc] initForWritingWithMutableData:data];
[archiver encodeFloat:50 forKey:@"age"];
[archiver encodeObject:@"jack" forKey:@"name"];
[archiver finishEncoding]; //結束添加對象到data中
[archiver release];
[data writeToFile:homePath atomically:YES];//將data寫到文件中保存在磁盤上
NData *content= [NSData dataWithConenteOfFile:homePath ];
NSKeyedUnarchiver *unarchiver = [[NSKeyedUnarchiver alloc] initForReadingWithData:content];
float age = [unarchiver decodeFloatForKey:@"age"];
NSString *name = [unarchiver decodeObjectForKey:@"name"];
好了,就這樣,自定義的歸檔和解歸檔的使用就這樣了。