Swift语言精要 - 序列化和反序列化
在swift中你可以把一个对象转换成为数据,你所要做的就是
首先,你需要让对象实现NSObject和NSCoding协议。
其次,实现以下两个方法:
encodeWithCoder
init(coder aDecoder: NSCoder) // 一个带NSCoder参数的初始化器
例子代码:
class SerializableObject : NSObject, NSCoding { var name : String? func encodeWithCoder(aCoder: NSCoder) { aCoder.encodeObject(name!, forKey:"name") } override init() { self.name = "My Object" } required init(coder aDecoder: NSCoder) { self.name = aDecoder.decodeObjectForKey("name") as? String } }
如果对象实现了NSCoding协议,那么它就能被转换成为NSData对象。
NSKeyedArchiver - 序列化
NSKeyedUnarchiver - 反序列化
例子代码:
let anObject = SerializableObject() anObject.name = "My Thing That I'm Saving" // Converting it to data let objectConvertedToData = NSKeyedArchiver.archivedDataWithRootObject(anObject) // Converting it back // Note that the conversion might fail, so 'unarchiveObjectWithData' returns // an optional value. So, use 'as?' to check to see if it worked. let loadedObject = NSKeyedUnarchiver.unarchiveObjectWithData(objectConvertedToData) as? SerializableObject print(loadedObject?.name) //"My Thing That I'm Saving"
技术改变世界