如何找到符合KVC标准的Objective-C对象的所有属性键?

arm*_*ahg 25 cocoa properties introspection objective-c key-value-observing

是否有一个方法返回符合NSKeyValueCoding协议的对象的所有键?

沿着这条线的东西[object getPropertyKeys]将返回NSString对象的NSArray.它适用于任何符合KVC标准的对象.这种方法存在吗?到目前为止,我还没有找到任何搜索Apple文档的内容.

谢谢,G.

oxi*_*gen 38

#import "objc/runtime.h"

unsigned int outCount, i;

objc_property_t *properties = class_copyPropertyList([self class], &outCount);
for(i = 0; i < outCount; i++) {
    objc_property_t property = properties[i];
    const char *propName = property_getName(property);
    if(propName) {
            const char *propType = getPropertyType(property);
            NSString *propertyName = [NSString stringWithUTF8String:propName];
            NSString *propertyType = [NSString stringWithUTF8String:propType];
    }
}
free(properties);
Run Code Online (Sandbox Code Playgroud)

  • 这个方法在哪里:`getPropertyType(property)`定义了什么? (9认同)
  • 此代码仅收集在对象类中直接声明的属性.要获取所有对象的属性,还需要遍历超类链并收集这些类的属性. (5认同)
  • 添加#import"objc/runtime.h" (4认同)
  • 这只获取用`@ property`语法声明的键.通过实现符合方法(或方法对)和/或覆盖核心KVC处理方法(即valueForUndefinedKey:,setValue:forUndefinedKey :),类可以与其他keyPath符合KVC.不幸的是,没有办法*明确*获得任意类符合KVC标准的密钥.换句话说,不要依赖于此. (2认同)
  • @chakrit 他可能定义了一个函数来解析 property_getAttributes 的结果以提取类型名称。您可以查看[此页面](https://developer.apple.com/library/mac/documentation/cocoa/conceptual/objcruntimeguide/Articles/ocrtPropertyIntrospection.html#//apple_ref/doc/uid/TP40008048-CH101-SW6 )有关此答案和相关代码的更多详细信息。 (2认同)