在正常项目中,需要将模型model本地化存储就必须用到解归档,解归档需要将模型中的所有的属性都一一写一遍非常麻烦,可以通过runtime快速完成自动解归档操作。
// 归档
func encode(with aCoder: NSCoder) {
var c = self.classForCoder
while c != NSObject.self {
var count: UInt32 = 0
// 获得class中所有属性
guard let ivars = class_copyIvarList(c, &count) else { return }
for i in 0..<count {
let key = NSString(utf8String: ivar_getName(ivars[Int(i)])!)! as String
let value = self.value(forKey: key)
aCoder.encode(value, forKey: key)
}
// 获得父类
c = c.superclass()!
// 释放
free(ivars)
}
}
// 解归档
required init?(coder aDecoder: NSCoder) {
super.init()
var c = self.classForCoder
while c != NSObject.self {
var count: UInt32 = 0
// 获得class中所有属性
guard let ivars = class_copyIvarList(c, &count) else { return }
for i in 0..<count {
let key = NSString(utf8String: ivar_getName(ivars[Int(i)])!)! as String
let value = aDecoder.decodeObject(forKey: key)
self.setValue(value, forKey: key)
}
// 获得父类
c = c.superclass()!
// 释放
free(ivars)
}
}