我正在编写一个实现KVO
的基类,我想推断该类的dynamic
属性的名称。例如:
class BaseClass {
func beginObserving() {
// What are the dynamic attributes to observe?
// In the case of "SubClass" below, it should be ["name"]
let attributes = ???
for attribute in attributes {
self.addObserver(self, forKeyPath: attribute, options: [.New, .Old], context: &KVOContext)
}
}
}
class SubClass : BaseClass {
dynamic var name: String!
}
类别列表';swift中的属性解释了如何使用Mirror
(反射)来实现这一点,但它似乎不适用于dynamic
vars(即,如果我删除了dynamic
关键字,则链接的代码将适用于这种情况)。
您可以使用标准的<objc/runtime.h>
函数:
class MyObject {
dynamic var identifier = 0
func dynamicProperties() -> [String] {
var dynamicProperties = [String]()
var propertyCount = UInt32(0)
let properties = class_copyPropertyList(object_getClass(self), &propertyCount)
for var i = 0; i < Int(propertyCount); i++ {
let property = properties[i]
let propertyName = property_getName(property)
dynamicProperties.append(String(CString: propertyName, encoding: NSUTF8StringEncoding)!)
}
free(properties)
return dynamicProperties
}
}
--
如果您希望子类不仅显示其属性,还显示其超类的属性,您可以执行以下操作:
class BaseClass {
dynamic var identifier = 0
func dynamicProperties() -> [String] {
var dynamicProperties = [String]()
var propertyCount = UInt32(0)
let properties = class_copyPropertyList(object_getClass(self), &propertyCount)
for var i = 0; i < Int(propertyCount); i++ {
let property = properties[i]
let propertyName = property_getName(property)
dynamicProperties.append(String(CString: propertyName, encoding: NSUTF8StringEncoding)!)
}
free(properties)
return dynamicProperties
}
}
class SubClass : BaseClass {
dynamic var name: String!
override func dynamicProperties() -> [String] {
var dynamicProperties = super.dynamicProperties()
var propertyCount = UInt32(0)
let properties = class_copyPropertyList(object_getClass(self), &propertyCount)
for var i = 0; i < Int(propertyCount); i++ {
let property = properties[i]
let propertyName = property_getName(property)
dynamicProperties.append(String(CString: propertyName, encoding: NSUTF8StringEncoding)!)
}
free(properties)
return dynamicProperties
}
}