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