swift3.0 运用Runtime实现model转字典

 1 func objectToDic(_ model: WYUserModel) -> [String: AnyObject] {
 2         
 3         var dic = [String: AnyObject]()
 4         var count: UInt32 = 0
 5         let properties = class_copyPropertyList(model.classForCoder, &count)
 6         for index in 0..<Int(count) {
 7 
 8             guard let pty = properties?[index],
 9                 let cName = property_getName(pty),
10                 let name = String(utf8String: cName) else {
11                     continue
12             }
13             if let value = model.value(forKey: name) {
14                 dic.updateValue(value as AnyObject, forKey: name)
15             } else {
16                 let null = NSNull()
17                 dic.updateValue(null, forKey: name)
18             }
19         }
20         free(properties)
21         return dic
22     }

 

posted @ 2017-02-07 09:13  乐启榜  阅读(735)  评论(0编辑  收藏  举报