Swift——解档和归档

1.对用户的模型数据(自定义类:HCUserModel)进行归档和解档

1.1 需要遵循NSCoding协议

1.2 需要实现func encode(with aCoder: NSCoder){}归档方法

1.3需要实现 required init(coder aDecoder: NSCoder){}解档方法

 

import UIKit

class 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, .userDomainMask, true).first!
        accountPath+="/userAccount.plist"
        let account=NSKeyedUnarchiver.unarchiveObject(withFile: accountPath) as? YMUserAccount

 

 

 

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值