1. 需要遵守 NSCoding协议
2. 实现 NSCoding 的两个方法
// MARK: --------------- nscoding 必须实现下面两个方法否则 会报错
/// 编码 --> obj
/// 解档方法,aDecoder解码器,将保存在磁盘的二进制文件转换成对象,和反序列化很像
required init?(coder aDecoder: NSCoder) {
access_token = aDecoder.decodeObjectForKey("access_token") as! String;
/// 因为decodeObjectForKey 返回的是 anyObject 所有要在后面用as! string 指明它是string类型,
expires_in = aDecoder.decodeDoubleForKey("expires_in");
/// decodeIntegerForKey, 已经指明是 int类型, 所以不用再用 as
expires_Date = aDecoder.decodeObjectForKey("expires_Date") as! NSDate;
uid = aDecoder.decodeObjectForKey("uid") as! String;
}
/// obj --> 编码
func encodeWithCoder(aCoder: NSCoder) {
aCoder.encodeObject(access_token, forKey: "access_token");
aCoder.encodeDouble(expires_in, forKey: "expires_in");
aCoder.encodeObject(expires_Date, forKey: "expires_Date");
aCoder.encodeObject(uid, forKey: "uid");
}
3 . 调用归档/ 反归档方法
// 沙盒路径
staticlet searchPath =NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.DocumentDirectory,NSSearchPathDomainMask.UserDomainMask,true).last;
staticlet filePath = searchPath!.stringByAppendingString("/userAccount.plist");
/// 保存账号信息,
/// 保存账号信息,
func saveAccount() {
/// swift 中如果想用 静态变量, 需要用 类ming.静态变量
NSKeyedArchiver.archiveRootObject(self, toFile: CCUserAccountToken.filePath);
print(CCUserAccountToken.filePath);
}
/// 读取账号信息
class func loadAccount() -> CCUserAccountToken?{
print(CCUserAccountToken.filePath)
// 读取账号信息
if let account = NSKeyedUnarchiver.unarchiveObjectWithFile(CCUserAccountToken.filePath) as? CCUserAccountToken{
// 判断是否过期
let date = account.expires_Date.dateByAddingTimeInterval(account.expires_in);
if date.compare(NSDate()) == NSComparisonResult.OrderedDescending{
return account;
}
}
return nil;
}