1.怎么實(shí)現(xiàn)模型轉(zhuǎn)字典呢?R-U-N-T-I-M-E
import Foundation
extension NSObject{
/// 我們只要調(diào)用這個(gè)方法就好了.
/// 通過字典設(shè)置屬性值(運(yùn)用場景,可以用來實(shí)現(xiàn)模型轉(zhuǎn)字典的)
///
/// - Parameter dic: [屬性名:屬性值]
/// - Returns: 是否設(shè)置成功
func setValueOfProperty(dic:[String:String])->Bool{
let allPropertys = self.propertyList()
for key in allPropertys {
self.setValue(dic[key], forKey: key)
}
return true
}
/// 獲取屬性值
///
/// - Returns: 返回獲取到的屬性值數(shù)組
func getValueOfProperty()->[String]{
let allPropertys = self.propertyList()
var values = [String]()
for key in allPropertys {
let val = self.value(forKey: key) as? String ?? ""
values.append(val)
}
return values
}
///[使用運(yùn)行時(shí)]獲取當(dāng)前類所有的屬性數(shù)組
func propertyList() -> [String] {
var count :UInt32 = 0
//獲取‘類’的屬性列表
guard let list = class_copyPropertyList(self.classForCoder, &count) else{
return []
}
var arr = [String]()
for i in 0..<Int(count) {
//根據(jù)下標(biāo) 獲取屬性
let a = list[i]
//獲取屬性的名稱
let cName = property_getName(a)
let n = String(utf8String:cName)
arr.append(n ?? "")
}
// 在這個(gè)方法里面創(chuàng)建數(shù)據(jù)表.
if tableViewIsExists() == false{
createTable(arr: arr)
}
free(list)
return arr
}
}