首页 > 代码库 > swift中使用对象归档进行数据本地

swift中使用对象归档进行数据本地

对象归档是ios持久化中的其中一种,也是很常用的一种。现在来看看swift是如何实现的。实现要点
1),必须实现NSCoding的协议

import UIKitlet path=(NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.DocumentDirectory,NSSearchPathDomainMask.UserDomainMask, true)[0] as String).stringByAppendingString("user.data")class User: NSObject,NSCoding {    var age:Int = 0    var name:String?    init() {        super.init()    }    init(coder aDecoder: NSCoder!)    {        super.init()        self.age=aDecoder.decodeIntegerForKey("age")        self.name=aDecoder.decodeObjectForKey("name") as? String    }    func encodeWithCoder(aCoder: NSCoder!) {        aCoder.encodeInteger(self.age, forKey: "age")        aCoder.encodeObject(self.name, forKey: "name")    }    class func save(user:User)->Bool{        return NSKeyedArchiver.archiveRootObject(user, toFile: path)    }        class func user()->User?{      return  NSKeyedUnarchiver.unarchiveObjectWithFile(path) as? User    }}

 

其中注意是
1.实现init(coder aDecoder: NSCoder!)后,默认的init()构造方法会没了,所以要把默认的init()实现一下,或者是自定义其他的构造方法。
2.从文件中恢复数据的时候,返回的可能是空,所以在方法返回值的地方要注意一下

如有不妥,望流浪(大牛)指正