获取班级的所有钥匙

Vic*_*ler 6 key-value-coding ios swift

最近我使用协议func setValue(_ value: AnyObject?, forKey key: String)的功能通过以下方式NSKeyValueCoding更改 a 的文本颜色: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)
    }
}
Run Code Online (Sandbox Code Playgroud)

关于这个问题的答案。它工作完美。

但我在这里的回答是:

我如何知道该类提供的名称(如textColor上面使用的)是什么?

我试图在文档中找到任何获取所有名称的内容,但到目前为止,我还没有找到任何内容来获取类提供的密钥,如上述情况。

Ada*_*ley 5

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));
}
Run Code Online (Sandbox Code Playgroud)

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

编辑 - swift 也有基本的反射:/sf/answers/1684891281/