归档&解档、静态单例(swift)

2016-11-07  本文已影响0人  会飞的水珠

1.在class OAuthViewController:UIViewController

// 3.从字典中取出昵称和用户头像地址(account :UserAccount)

account.screen_name = userInfoDict["screen_name"]as?String

account.avatar_large = userInfoDict["avatar_large"]as?String

// 4.将account对象保存

NSKeyedArchiver.archiveRootObject(account, toFile: UserAccountViewModel.shareIntance.accountPath)

2.在class UserAccount:NSObject,NSCoding 

// MARK:-归档&解档

///解档的方法

requiredinit?(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

}

///归档方法

funcencodeWithCoder(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")

}

3.在其它类中提取沙河里的值

// 1.从沙盒中读取中归档的信息

var accountPath =NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask,true).first!

accountPath = (accountPath as NSString).stringByAppendingPathComponent("account.plist")

account=NSKeyedUnarchiver.unarchiveObjectWithFile(accountPath) as? UserAccount

//取出值,如下

account.screen_name

上一篇 下一篇

猜你喜欢

热点阅读