Swift 歸檔解歸檔

2021-07-10 23:30:25 字數 956 閱讀 7225

swift中物件進行歸檔寫入檔案時需要對物件屬性進行歸檔操和解歸檔操作

,物件方法中需重寫以下兩個方法

//從nsobject解析回來

init(coder adecoder:nscoder!)

//編碼成object

func encodewithcoder(acoder:nscoder!)

歸檔,解歸檔需要使用到nskeyedarchiver和nskeyedunarchiver來實現。

//儲存資料

letdata

= nsmutabledata()

let archiver = nskeyedarchiver(forwritingwithmutabledata: data)

archiver.encodeobject(userdata,forkey: "userlist")

archiver.finishencoding()

//資料寫入

data

.writetofile(datafilepath, atomically: true)

//讀取資料

//獲取本地資料檔案位址

let path =

self

.datafilepath()

//讀取檔案資料

letdata

= nsdata(contentsoffile: path)

//解碼器

let unarchiver = nskeyedunarchiver(forreadingwithdata: data

!) userlist = unarchiver.decodeobjectforkey("userdata") as!

array

//結束解碼

unarchiver.finishdecoding()

swift 本地歸檔 解檔儲存

1.對使用者的模型資料 自定義類 hcusermodel 進行歸檔和解檔 1.1 需要遵循nscoding協議 1.2 需要實現func encode with acoder nscoder 歸檔方法 1.3需要實現 required init coder adecoder nscoder 解檔方法...

iOS 歸檔解檔

開發過程中有時需要儲存一些輕量級的資料,對於ios提供的幾種資料儲存方式在這時最合適當屬物件歸檔 nscoding 但是將物件資料進行歸檔解檔時候需要實現兩個方法 encodewithcoder和initwithencoder。encodewithcoder 編碼 initwithcoder 解碼使...

iOS 歸檔 解檔

1.新建類datacache 歸檔 void cachewithdata id data withfile nsstring file 解檔 id archivewithfile nsstring file 2.使用 儲存路徑 college mouth.arc 在虛擬機器上,簡單的寫可以找到路徑,...