標籤:
原文:http://blog.sina.com.cn/s/blog_7124765801015imx.html
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"];
好了,就這樣,自訂的歸檔和解歸檔的使用就這樣了。
IOS --- 對象歸檔