1.获取沙盒路径
//1.获取沙盒路径
var accountPath = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true).first!
accountPath = (accountPath as NSString).appendingPathComponent("account.plist")
2.归档
NSKeyedArchiver.archiveRootObject(account, toFile: accountPath)
3.解档
account = NSKeyedUnarchiver.unarchiveObject(withFile: accountPath) as? GGAccount
归档对象必须遵守NSCoding协议
例如创建了一个账户类account.swift
1.遵守协议
class GGAccount: NSObject,NSCoding{
...
}
2.必须实现2个方法 public func encode(with aCoder: NSCoder),public init?(coder aDecoder: NSCoder)
class GGAccount: NSObject,NSCoding{
...
// 归档&解档
// 解档
required init?(coder aDecoder: NSCoder) {
access_token = aDecoder.decodeObject(forKey: "access_token") as? String
uid = aDecoder.decodeObject(forKey: "uid") as? String
expires_date = aDecoder.decodeObject(forKey: "expires_date") as? NSDate
name = aDecoder.decodeObject(forKey: "name") as? String
avatar_large = aDecoder.decodeObject(forKey: "avatar_large") as? String
}
// 归档
func encode(with aCoder: NSCoder) {
aCoder.encode(access_token, forKey: "access_token")
aCoder.encode(uid, forKey: "uid")
aCoder.encode(expires_date, forKey: "expires_date")
aCoder.encode(name, forKey: "name")
aCoder.encode(avatar_large, forKey: "avatar_large")
}
}
网友评论