swift归档解档

    

        //将用户的信息保存到本地

        NSKeyedArchiver.archiveRootObject(account, toFile: self.accoutPath)

        

   //解档

        account = NSKeyedUnarchiver.unarchiveObjectWithFile(accoutPath) as? UserAccount

// MARK: - 归档 & 解档
/// 归档 -> 将当前对象归档保存至二进制文件之前被调用
///
/// - parameter aCoder: 编码器
func encodeWithCoder(aCoder: NSCoder) {
    aCoder.encodeObject(access_token, forKey: "access_token")
    aCoder.encodeObject(expiresDate, forKey: "expiresDate")
    aCoder.encodeObject(uid, forKey: "uid")
    aCoder.encodeObject(screen_name, forKey: "screen_name")
    aCoder.encodeObject(avatar_large, forKey: "avatar_large")
}

/// 解档 -> 从二进制文件恢复成对象时调用,与网络的反序列化功能类似
///
/// - parameter aDecoder: 解码器
///
/// - returns: 用户账户对象
required init?(coder aDecoder: NSCoder) {
    access_token = aDecoder.decodeObjectForKey("access_token") as? String
    expiresDate = aDecoder.decodeObjectForKey("expiresDate") as? NSDate
    uid = aDecoder.decodeObjectForKey("uid") as? String
    screen_name = aDecoder.decodeObjectForKey("screen_name") as? String
    avatar_large = aDecoder.decodeObjectForKey("avatar_large") as? String
}
/// 将当前对象保存至沙盒
func saveUserAccount() {
    var path = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true).last!
    path = (path as NSString).stringByAppendingPathComponent("account.plist")

    print(path)

    NSKeyedArchiver.archiveRootObject(self, toFile: path)
}



你可能感兴趣的:(swift归档解档)