1. 程式人生 > >iOS swift-歸檔與解檔

iOS swift-歸檔與解檔

1.被歸檔的物件所在類必須遵守協議 NSCoding

2.被歸檔的物件所在類必須兩個函式來規定如何歸檔和解檔

// MARK:- 歸檔&解檔
/// 解檔的函式
init?(coder aDecoder: NSCoder) {
}
    
/// 歸檔的函式
func encodeWithCoder(aCoder: NSCoder) {
}

舉例:

被歸檔的物件所在類中(遵守協議 NSCoding)

UserAccount類

// MARK:- 屬性
/// 授權AccessToken
var access_token : String?
/// 使用者ID
var uid : String?
/// 過期日期
var expires_date : NSDate?
/// 暱稱
var screen_name : String?
/// 使用者的頭像地址
var avatar_large : String?

// MARK:- 歸檔&解檔
/// 解檔的函式
required init?(coder aDecoder: NSCoder) {
    access_token = aDecoder.decodeObjectForKey("access_token") as? String
    uid  = aDecoder.decodeObjectForKey("uid") as? String
    expires_date  = aDecoder.decodeObjectForKey("expires_date") as? NSDate
    avatar_large  = aDecoder.decodeObjectForKey("avatar_large") as? String
    screen_name  = aDecoder.decodeObjectForKey("screen_name") as? String
}

/// 歸檔的函式
func encodeWithCoder(aCoder: NSCoder) {
    aCoder.encodeObject(access_token, forKey: "access_token")
    aCoder.encodeObject(uid, forKey: "uid")
    aCoder.encodeObject(expires_date, forKey: "expires_date")
    aCoder.encodeObject(avatar_large, forKey: "avatar_large")
    aCoder.encodeObject(screen_name, forKey: "screen_name")
}

其它類中

歸檔

// 將account物件儲存
// 1.獲取沙盒路徑
var accountPath = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true).first!
accountPath = (accountPath as NSString).stringByAppendingPathComponent("account.plist")

// 2.儲存物件
NSKeyedArchiver.archiveRootObject(account, toFile: accountPath)

解檔

// 從沙盒中讀取歸檔的資訊
// 1.獲取沙盒路徑
var accountPath = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true).first!
accountPath = (accountPath as NSString).stringByAppendingPathComponent("account.plist")

// 2.讀取資訊
let account = NSKeyedUnarchiver.unarchiveObjectWithFile(accountPath) as? UserAccount