NSCoding序列化
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了NSCoding序列化相关的知识,希望对你有一定的参考价值。
一个类用于存储获取的用户登陆信息,让这个类实现NSCoping Protocol。然后实现协议里面的
required init?(coder aDecoder: NSCoder)方法和 func encodeWithCoder(aCoder: NSCoder)方法。然后就可以用
let data = NSKeyedArchiver.archivedDataWithRootObject(someObj)方法得到NSData对象,可以直接写入文件,或者直接NSStardardDefaults.setValue()方法,就可以序列化了
代码备忘:
import UIKit class UserInfo:NSObject,NSCoding{ private let iconkey = "iconkey" private let nicknamekey="nicknamekey" private let aboutMekey="aboutmekey" private let statuskey="statuskey" var icon:String var name:String var aboutMe:String var statustext:String init(dict:[String:AnyObject]) { self.icon = "" self.name = "" self.aboutMe = "" self.statustext = "" super.init() setValuesForKeysWithDictionary(dict) } override func setValue(value: AnyObject?, forUndefinedKey key: String) { // } func encodeWithCoder(aCoder: NSCoder){ aCoder.encodeObject(icon, forKey: iconkey) aCoder.encodeObject(name, forKey: nicknamekey) aCoder.encodeObject(aboutMe, forKey: aboutMekey) aCoder.encodeObject(statustext,forKey: statuskey) } required init?(coder aDecoder: NSCoder){ self.icon = aDecoder.decodeObjectForKey(iconkey) as! String self.name = aDecoder.decodeObjectForKey(nicknamekey) as! String self.aboutMe = aDecoder.decodeObjectForKey(aboutMekey) as! String self.statustext = aDecoder.decodeObjectForKey(statuskey) as! String }// NS_DESIGNATED_INITIALIZER let ui:UserInfo = UserInfo(dict: dict); let data = NSKeyedArchiver.archivedDataWithRootObject(ui) ud.setValue(data, forKey: LoginInfo);
读取的时候用下面的
if let userinfo = NSKeyedUnarchiver.unarchiveObjectWithData(NSUserDefaults.standardUserDefaults().objectForKey(LoginInfo) as! NSData) as? UserInfo{ (self.view.viewWithTag(100) as! UIImageView).yy_setImageWithURL(NSURL(string: userinfo.icon), options: YYWebImageOptions.ProgressiveBlur); (self.view.viewWithTag(101) as! UILabel).text = userinfo.name; (self.view.viewWithTag(102) as! UILabel).text = userinfo.aboutMe; (self.view.viewWithTag(103) as! UILabel).text = userinfo.statustext; }
以上是关于NSCoding序列化的主要内容,如果未能解决你的问题,请参考以下文章