天天看點

iOS開發之資料存儲之NSData

1、概述

使用archiverootobject:tofile:方法可以将一個對象直接寫入到一個檔案中,但有時候可能想将多個對象寫入到同一個檔案中,那麼就要使用nsdata來進行歸檔對象。

nsdata可以為一些資料提供臨時存儲空間,以便随後寫入檔案,或者存放從磁盤讀取的檔案内容。可以使用[nsmutabledata data]建立可變資料空間。

iOS開發之資料存儲之NSData

2、歸檔2個person對象到同一檔案中

歸檔(編碼):

// 建立一塊可變資料區

nsmutabledata *data = [nsmutabledata data];

// 将資料區連接配接到一個nskeyedarchiver對象

nskeyedarchiver *archiver = [[[nskeyedarchiver alloc] initforwritingwithmutabledata:data] autorelease];

// 開始存檔對象,存檔的資料都會存儲到nsmutabledata中

[archiver encodeobject:person1 forkey:@"person1"];

[archiver encodeobject:person2 forkey:@"person2"];

// 存檔完畢(一定要調用這個方法)

[archiver finishencoding];

// 将存檔的資料寫入檔案

[data writetofile:path atomically:yes];

3、從同一檔案中恢複2個person對象

恢複(解碼):

// 從檔案中讀取資料

nsdata *data = [nsdata datawithcontentsoffile:path];

// 根據資料,解析成一個nskeyedunarchiver對象

nskeyedunarchiver *unarchiver = [[nskeyedunarchiver alloc] initforreadingwithdata:data];

person *person1 = [unarchiver decodeobjectforkey:@"person1"];

person *person2 = [unarchiver decodeobjectforkey:@"person2"];

// 恢複完畢

[unarchiver finishdecoding];

4、利用歸檔實作深複制

比如對一個person對象進行深複制:

// 臨時存儲person1的資料

nsdata *data =

[nskeyedarchiver archiveddatawithrootobject:person1];

// 解析data,生成一個新的person對象

student *person2 =

[nskeyedunarchiver unarchiveobjectwithdata:data];

// 分别列印記憶體位址

nslog(@"person1:0x%x", person1); // person1:0x7177a60

nslog(@"person2:0x%x", person2); // person2:0x7177cf0