歸檔以及反歸檔

2021-07-05 09:11:03 字數 1627 閱讀 6716

歸檔和反歸檔

複雜的物件我們並不能通過writetofile型別的方法寫入到檔案中。 這裡的複雜物件指的是在foundation框架內部存在的資料類,這個負載物件至少包含有乙個例項物件

如果想要進行歸檔和反歸檔操作,則必須遵守 協議

我們在歸檔和解檔操作時, 每乙個需要乙個鍵. 並且歸檔時是什麼鍵, 那麼解檔時就需要用到什麼鍵值, 我推薦大家使用巨集定義, 這樣的話不至於混淆.並且在寫的時候最好見名知意.如圖:

構建乙個學生類, 包含姓名, 年齡, 性別三個屬性, 宣告初始化方法。並且巨集定義鍵

接下來在.m檔案中實現解檔和歸檔的方法

歸檔我們使用方法:

- (void)encodewithcoder:(nscoder *)acoder

在viewcontroller中建立學生兩個物件

nsarray *students = @[stu1,stu2];//然後將學生物件存到陣列中.

//然後我們獲取儲存資料的路徑並指定儲存格式

nsarray

*paths = nssearchpathfordirectoriesindomains(nsdocumentdirectory, nsuserdomainmask,

yes);

nsstring *documentspath = paths.firstobject;

nsstring

@"students.plist"];

呼叫nskeyedarchiver方法進行歸檔操作 [

nskeyedarchiver

archiverootobject:students tofile:stupath];

執行之後我們的資料就會儲存在沙盒資料夾中.

如果需要取出資料的話, 就需要我們做反歸檔操作, 在student.m檔案寫出student的反歸檔方法,注意鍵要和歸檔時一樣~! 巨集定義的優勢瞬間就體現了出來

- (id)initwithcoder:(nscoder *)adecoder

return self; }

在viewcontroller中定義乙個陣列用來接收資料.

反歸檔使用方法nskeyedunarchiver實現

nsarray *unarcstus = [nskeyedunarchiver

unarchiveobjectwithfile:stupath];

列印一下資料, 看是否取出了歸檔時存入的資料

可以看到利用反歸檔方式取出了存入的資料.

如果歸檔/反歸檔會出錯, 我總結道德常見錯誤有:

1. 野指標/記憶體洩露(哪兒裡都常見,如果用mrc環境的話, 注意引用計數的平衡)

2. 鍵值不統一(用巨集定義基本不會存在)

3. 錯誤的路徑

歸檔和反歸檔以及檔案管理

關於歸檔和反歸檔,菜菜說用的不那麼多,經常用的nsdata 我們能直接進行歸檔的只有簡單資料型別 四大類 比如nsstring nsmutablestring,nsarray,nsmutablearray,nsdictionary,nsmutabledictionary nsdata,nsmutab...

歸檔與反歸檔

建立一對.h m檔案nsobject h中遵守nscoding協議 定義屬性 在.m檔案中 反序列比 id initwithcoder nscoder adecoder return self 序列比 void encoderwithcoder nscoder acoder 在需要使用的地方 m 使...

歸檔, 反歸檔, 清除快取

1.寫巨集的時候可以建乙個只有header的標頭檔案 2.pragma mark 如果想要實現歸檔和反歸檔的操作需要簽訂乙個協議nscoding void encodewithcoder nscoder acoder id initwithcoder nscoder adecoder return ...