class Model: NSObject, NSCoding { dynamic var name = "" dynamic var age = 0 override init() { } // 归档 func encode(with aCoder: NSCoder) { var count: UInt32 = 0 guard let ivars = class_copyIvarList(self.classForCoder, &count) else { return } for i in 0 ..< count { let ivar = ivars[Int(i)] let name = ivar_getName(ivar) let key = NSString.init(utf8String: name!) as! String if let value = self.value(forKey: key) { aCoder.encode(value, forKey: key) } } free(ivars) } // 解档 required init?(coder aDecoder: NSCoder) { super.init() var count: UInt32 = 0 guard let ivars = class_copyIvarList(self.classForCoder, &count) else { return } for i in 0 ..< count { let ivar = ivars[Int(i)] let name = ivar_getName(ivar) let key = NSString.init(utf8String: name!) as! String if let value = aDecoder.decodeObject(forKey: key) { self.setValue(value, forKey: key) } } free(ivars) } }
使用runtime解档归档的时候一定要在属性前加上dynamic 关键字,并且不能使用可选属性*
######下面我们准备一下要归档的模型和文件路径
1 2 3 4 5
let model = Model() model.name = "FlyChang" model.age = 25 var path = NSSearchPathForDirectoriesInDomains(.cachesDirectory, .userDomainMask, true).last path = path! + "/Model"
归档
1 2 3 4 5
let data = NSMutableData() let archiver = NSKeyedArchiver(forWritingWith: data) archiver.encode(model, forKey: "model") archiver.finishEncoding() data.write(toFile: path!, atomically: true)
解档
1 2 3 4
let data = NSData(contentsOfFile: path!) let unarchiver = NSKeyedUnarchiver(forReadingWith: data) let model = unarchiver.decodeObject(forKey: "model") as! Model unarchiver.finishDecoding()