标签:ade runtime let swift false 归档 strong guard font
Swift 使用Runtime对模型进行归档解档
func encode(with aCoder: NSCoder) {
var count: UInt32 = 0
let propertyList = class_copyPropertyList(self.classForCoder, &count)
for index in 0..<Int(count) {
guard let pty = propertyList?[index],
let cName = property_getName(pty),
let name = String(utf8String: cName) else {
continue
}
let value = self.value(forKey: name)
aCoder.encode(value, forKey: name)
}
free(propertyList)
}
required init?(coder aDecoder: NSCoder) {
super.init()
var count: UInt32 = 0
let propertyList = class_copyPropertyList(self.classForCoder, &count)
for index in 0..<Int(count) {
guard let pty = propertyList?[index],
let cName = property_getName(pty),
let name = String(utf8String: cName) else {
continue
}
let value = aDecoder.decodeObject(forKey: name)
self.setValue(value, forKey: name)
}
free(propertyList)
}
在取值和赋值都是使用KVC:
取值:
let value = self.value(forKey: name)
aCoder.encode(value, forKey: name)
赋值:
let value = aDecoder.decodeObject(forKey: name)
self.setValue(value, forKey: name)
标签:ade runtime let swift false 归档 strong guard font
原文地址:http://www.cnblogs.com/PLA-Artillery/p/6669994.html