Swift 归档解档

// 遵守 NSCoding 与OC 没有多大变化

 

    // MARK : 解档 归档

    required init?(coder aDecoder: NSCoder) {

        access_token = aDecoder.decodeObjectForKey("access_token") as! String

        expires_in = aDecoder.decodeDoubleForKey("expires_in")

        expiresDate = aDecoder.decodeObjectForKey("expiresDate") as! NSDate

        uid = aDecoder.decodeObjectForKey("uid") as! String

        

        name = aDecoder.decodeObjectForKey("name") as? String

        avatar_large = aDecoder.decodeObjectForKey("avatar_large") as? String

    }

    

    

    func encodeWithCoder(aCoder: NSCoder) {

        aCoder.encodeObject(access_token, forKey: "access_token")

        aCoder.encodeDouble(expires_in, forKey: "expires_in")

        aCoder.encodeObject(expiresDate, forKey: "expires_in")

        aCoder.encodeObject(uid, forKey: "uid")

        

        aCoder.encodeObject(name, forKey: "name")

        aCoder.encodeObject(avatar_large, forKey: "avatar_large")

 

 

 

    // MARK: - 保存和加载文件

    /// 归档路径,swift中的类常量都是使用 static 来定义的

    static let accountPath = NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.DocumentDirectory, NSSearchPathDomainMask.UserDomainMask, true).last!.stringByAppendingPathComponent("account.plist")

    

    func saveAccount(){

        NSKeyedArchiver.archiveRootObject(self, toFile: UserAccount.accountPath)

    }

    

    // 加个? 表示返回可为空

    class func loadAccount() -> UserAccount? {

        if let account = NSKeyedUnarchiver.unarchiveObjectWithFile(accountPath) as? UserAccount {

            

            // 判断日期是否过期,根当前系统时间进行`比较`,低于当前系统时间,就认为过期

            // 过期日期`大于`当前日期,结果应该是降序

            if account.expiresDate.compare(NSDate()) == NSComparisonResult.OrderedDescending {

                return account

            }

        }

       return nil

    }

 

posted @ 2015-06-29 23:11  风中一场梦  阅读(1169)  评论(0编辑  收藏  举报