IOS --- 對象歸檔

來源:互聯網
上載者:User

標籤:

原文: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 --- 對象歸檔

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.