归档

要将一个类的对象属性进行归档保存,那么这个类必须遵守NSCoding协议,并且实现

func encode(with aCoder: NSCoder)

init?(coder aDecoder: NSCoder)

归档和解档的方法

下面是遵守NSCoding协议的类,已经实现了归档和解档的方法

import UIKit

class ZFSinaUserAccount: NSObject ,NSCoding{

    var access_token : String?
    var expires_date : Date?
    var expires_in : TimeInterval = 0.0 {
        didSet(old)
        {
            expires_date = Date.init(timeIntervalSinceNow: ZFSinaUserAccount.shareUserAccount.expires_in)
        }
    }
    var uid:String?
    var screen_name : String?
    var avatar_large : String?

    //单例
    static var shareUserAccount : ZFSinaUserAccount = {

        let userAccount = ZFSinaUserAccount()

        return userAccount

    }()

    //归档方法
    func encode(with aCoder: NSCoder) {
        aCoder.encode(access_token, forKey: "access_token")
        aCoder.encode(expires_date, forKey: "expires_date")
        aCoder.encode(uid, forKey: "uid")
        aCoder.encode(screen_name, forKey: "screen_name")
        aCoder.encode(avatar_large, forKey: "avatar_large")
    }

    //解档方法,这个方法必须在类中实现,不能在类的扩展中实现,required表示必须实现
    convenience required init?(coder aDecoder: NSCoder) {
        self.init()

        access_token = aDecoder.decodeObject(forKey: "access_token") as! String?
        expires_date = aDecoder.decodeObject(forKey: "expires_date") as! Date?
        uid = aDecoder.decodeObject(forKey: "uid") as! String?
        screen_name = aDecoder.decodeObject(forKey: "screen_name") as! String?
        avatar_large = aDecoder.decodeObject(forKey: "avatar_large") as! String?
    }
}

存档:

var accountPath = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true).first!
accountPath = (accountPath as NSString).appendingPathComponent("account.plist")

NSKeyedArchiver.archiveRootObject(ZFSinaUserAccount.shareUserAccount, toFile: accountPath)//存档

读档

var accountPath = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true).first!
accountPath = (accountPath as NSString).appendingPathComponent("account.plist")

if let account = (NSKeyedUnarchiver.unarchiveObject(withFile: accountPath) as? ZFSinaUserAccount) {

    ....
}

results matching ""

    No results matching ""