Objective-C中获取类(类对象)的属性列表利用runtime
Swift可以利用反射获取
class SuperClass: NSObject {
var name:String = "zym_chen"
var qq: String = "625271562"
}
class SubClass: SuperClass {
var age:Int = 1
var sex:Bool = true
class func test() {
let obj: SubClass = SubClass()
let morror = Mirror.init(reflecting: obj)
let superMorror = Mirror.init(reflecting: obj).superclassMirror
for (name, value) in (superMorror?.children)! {
print("父类属性名:\(name) 值: \(value)")
}
for (name, value) in (morror.children) {
print("子类属性名:\(name) 值: \(value)")
}
}
}
// 打印结果:
父类属性名:Optional("name") 值: zym_chen
父类属性名:Optional("qq") 值: 625271562
子类属性名:Optional("age") 值: 1
子类属性名:Optional("sex") 值: true
比起用runtime要方便, 而且可以分别获取对象仅属于自身的属性值和从父类继承的属性值.不过暂时Swift中反射的功能远还没有runtime强大