在Objective-C中获取对象的属性数组

Joh*_*ker 5 properties object objective-c

是否可以在Objective C中获取所有对象属性的数组?基本上,我想要做的是这样的事情:

- (void)save {
   NSArray *propertyArray = [self propertyNames];
   for (NSString *propertyName in propertyArray) {
      [self doSomethingCoolWithValue:[self valueForKey:propertyName]];
   }
}
Run Code Online (Sandbox Code Playgroud)

这可能吗?它似乎应该是,但我无法弄清楚我propertyNames应该采用什么方法 .

Joh*_*ker 9

我做了一些挖掘,并在Objective-C运行时编程指南中找到了我想要的东西.以下是我在原始问题中实现我想要做的事情,大量使用Apple的示例代码:

#import <Foundation/NSObjCRuntime.h>
#import <objc/runtime.h>

- (void)save {
    id currentClass = [self class];
    NSString *propertyName;
    unsigned int outCount, i;
    objc_property_t *properties = class_copyPropertyList(currentClass, &outCount);
    for (i = 0; i < outCount; i++) {
        objc_property_t property = properties[i];
        propertyName = [NSString stringWithCString:property_getName(property)];
        [self doSomethingCoolWithValue:[self valueForKey:propertyName]];
    }
}
Run Code Online (Sandbox Code Playgroud)

我希望这将帮助其他人寻找一种以编程方式访问对象属性名称的方法.