获取 class 的所有密钥

Get all the keys for a class

最近我使用函数 func setValue(_ value: AnyObject?, forKey key: String) of the NSKeyValueCoding 协议按以下方式更改 UIPickerDate 的文本颜色:

class ColoredDatePicker: UIDatePicker {

    var changed = false

    override func addSubview(view: UIView) {
       if !changed {
          changed = true
          self.setValue(UIColor(red: 0.42, green: 0.42, blue: 0.42, alpha: 1), forKey: "textColor")

       }
       super.addSubview(view)
    }
}

关于这个 question 中的答案。它完美运行。

但我的回答是:

我怎么知道 class 提供了哪些名称,如上面使用的 textColor

我正在尝试找到任何包含所有名称或文档的内容,但到目前为止我还没有找到任何可以获取 keys 的内容 class 就像上面的例子。

objective-c 运行时为属性提供这种类型的反射:

id UIDatePickerClass = objc_getClass("UIDatePicker");
unsigned int outCount, i;
objc_property_t *properties = class_copyPropertyList(UIDatePickerClass, &outCount);
for (i = 0; i < outCount; i++) {
    objc_property_t property = properties[i];
    fprintf(stdout, "%s %s\n", property_getName(property), property_getAttributes(property));
}

参考文档:https://developer.apple.com/library/mac/documentation/Cocoa/Reference/ObjCRuntimeRef/index.html#//apple_ref/c/func/class_copyPropertyList

编辑 - swift 也有基本的反映:

对于那些我们想要像@Adam 这样的 Swift 解决方案的人,这里是:

var propertiesCount : CUnsignedInt = 0
let propertiesInAClass  = class_copyPropertyList(UIDatePicker.self, &propertiesCount)
var propertiesDictionary : NSMutableDictionary = NSMutableDictionary()

for var i = 0; i < Int(propertiesCount); i++ {
    var property = propertiesInAClass[i]
    var propName = NSString(CString: property_getName(property), encoding: NSUTF8StringEncoding)
    println(propName)
}

Swift 4.1:

var propertiesCount: CUnsignedInt = 0
let propertiesInAClass = class_copyPropertyList(UIDatePicker.self, &propertiesCount)!
var propertiesDictionary: NSMutableDictionary = [:]

for i in 0..<propertiesCount {
    var property = propertiesInAClass[Int(i)]
    let propName = NSString(cString: property_getName(property), encoding: String.Encoding.utf8.rawValue)
    print(propName)
}

@Victor Sigler 和@dwlz 的一些更改,以获取所有键的当前值:

    var propertiesCount : CUnsignedInt = 0
    let propertiesInClass = class_copyPropertyList(UIDatePicker.self, &propertiesCount)
    print("Prperties:\(propertiesCount)")
    for i in 0..<propertiesCount
    {
        let property = propertiesInClass![Int(i)]
        let name = NSString(cString: property_getName(property), encoding: String.Encoding.utf8.rawValue)
        print("\(i + 1). Key:\(name!),value \(String(describing: self.value(forKey: name! as String)))")
    }