1.对用户的模型数据(自定义类:HCusermodel)进行归档和解档
1.1 需要遵循NSCoding协议
1.2 需要实现funcencode(with aCoder:NSCoder){}归档方法
1.3需要实现requiredinit(coder aDecoder:NSCoder){}解档方法
import UIKitclass YMUserAccount:NSObject,NSCoding { //MARK:-属性 //授权Acccesstoken var access_token:String? //过期时间-->秒 var expires_in:TimeInterval=0.0{ dIDSet{ expires_date=Date(timeIntervalSinceNow: expires_in) } } //用户ID var uID :String? //昵称 var screen_name:String? var avatar_large:String? //额外参数 var expires_date:Date? //MARK:-自定义构造函数 init(dic:[String:AnyObject]) { super.init() access_token=dic["access_token"] as! String? uID=dic["uID"] as! String? expires_in=dic["expires_in"] as! TimeInterval } overrIDe func setValuesForKeys(_ keyedValues: [String : Any]) { } //MARK:-解档 归档 //解档的方法 required init?(coder aDecoder: NSCoder) { super.init() access_token=aDecoder.decodeObject(forKey: "access_token") as! String? uID=aDecoder.decodeObject(forKey: "uID") as! String? expires_date=aDecoder.decodeObject(forKey: "expires_date") as! Date? screen_name=aDecoder.decodeObject(forKey: "screen_name") as! String? avatar_large=aDecoder.decodeObject(forKey: "avatar_large") as! String? } //归档的方法 func encode(with aCoder: NSCoder) { aCoder.encode(access_token,forKey: "access_token") aCoder.encode(uID,forKey: "uID") aCoder.encode(expires_date,forKey: "expires_date") aCoder.encode(screen_name,forKey: "screen_name") aCoder.encode(avatar_large,forKey: "avatar_large") }}
将account对象保存到本地 //获取沙盒路径 var accountPath=NSSearchPathForDirectorIEsInDomains(.documentDirectory,.userDomainMask,true).first! accountPath+="/userAccount.pList" print("路径:"+accountPath); NSKeyedArchiver.archiveRootObject(account,tofile: accountPath)
//从沙盒中读取归档的信息 var accountPath=NSSearchPathForDirectorIEsInDomains(.documentDirectory,true).first! accountPath+="/userAccount.pList" let account=NSKeyedUnarchiver.unarchiveObject(withfile: accountPath) as? YMUserAccount总结
以上是内存溢出为你收集整理的Swift 解档和归档全部内容,希望文章能够帮你解决Swift 解档和归档所遇到的程序开发问题。
如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)