实现原理
通过获取类的属性,填充和读取数据
代码实现
func initWithDic( dic:Dictionary<String, Any>) {
var outCount:UInt32 = 0
let properties = class_copyPropertyList(self.classForCoder, &outCount)
for i in 0..<numericCast(outCount) {
let property = properties![i]
let name = property_getName(property);
let proper = String.init(cString: name)
if (dic[proper] != nil) {
self.setValue(dic[proper], forKey: proper)
}
}
}
func toDic() -> Dictionary<String, Any> {
var dic:Dictionary<String, Any>=Dictionary<String, Any>()
var outCount:UInt32 = 0
let properties = class_copyPropertyList(self.classForCoder, &outCount)
for i in 0..<numericCast(outCount) {
let property = properties![i]
let name = property_getName(property);
let proper = String.init(cString: name)
let value = self.perform(Selector(proper))
dic[proper] = value
}
return dic
}
注意事项
swift4.0中继承 NSObject 的 swift class 不再默认 BRIDGE 到 OC,如果我们想要使用的话我们就需要在class前面加上@objcMembers 这么一个关键字
@objcMembers class FunctionMyModel: NSObject {
var FUNCTION_NAME:String! = ""
var FUNCTION_FACE:String! = "
}