swift数据持久化--归档

在数据存储上比较常用,下面给大家简单介绍一下归档:

      一般情况下我们先从网络上获取json数据,然后简历数据模型,最后将数据模型存储,但是归档不是所有的数据类型都可以存储,归档存储的类型包括:NSData、NSString、NSNumber、NSDate、NSArray、NSDictionary五种类型,如果不能归档,我们可以尝试转化为这五种中的任何一种再进行存储

//这里要遵守nscoding协议
class UserData: NSObject , NSCoding {

    var expires_Date:NSDate?
    var uid:String?
    var avatar_large: String?
    var screen_name: String?
    
    // 1.0用字典初始化模型
    init(dict:[String:AnyObject]) {
        super.init()
        setValuesForKeysWithDictionary(dict)
    }
    //如果字典中又缺少值的情况不会报错
    override func setValue(value: AnyObject?, forUndefinedKey key: String) {
        print(key)
    }
    
    
    //MARK: NACODING协议
    //2.0 将对象写入到文件中
    func encodeWithCoder(aCoder: NSCoder)
    {
        aCoder.encodeObject(access_token, forKey: "access_token")
        aCoder.encodeObject(expires_in, forKey: "expires_in")
        aCoder.encodeObject(uid, forKey: "uid")
        aCoder.encodeObject(expires_Date, forKey: "expires_Date")
    }
    //3.0 从文件中读取对象
    required init?(coder aDecoder: NSCoder)
    {
        access_token = aDecoder.decodeObjectForKey("access_token") as? String
        expires_in = aDecoder.decodeObjectForKey("expires_in") as? NSNumber
        uid = aDecoder.decodeObjectForKey("uid") as? String
        expires_Date = aDecoder.decodeObjectForKey("expires_Date") as? NSDate
    }
    
    //下面定义两个方法供外部使用
    
   //4.0 保存授权模型 
    func saveAccount()
    {
        let path = NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.CachesDirectory, NSSearchPathDomainMask.UserDomainMask, true).last!
        let filePath = (path as NSString).stringByAppendingPathComponent("user.plist")
        print("filePath \(filePath)")
        NSKeyedArchiver.archiveRootObject(self, toFile: filePath)
    }
    
    //5.0 加载授权模型
    class func loadAccount() -> UserAccount? {
        let path = NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.CachesDirectory, NSSearchPathDomainMask.UserDomainMask, true).last!
        let filePath = (path as NSString).stringByAppendingPathComponent("user.plist")
        print("filePath \(filePath)")

        let account =  NSKeyedUnarchiver.unarchiveObjectWithFile(filePath) as? UserAccount
        return account
    }



转载于:https://my.oschina.net/ShangGuanchen/blog/634159

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值