在 Objective-C 中获取对象的属性数组 [英] Getting an array of properties for an object in Objective-C
问题描述
是否可以在 Objective C 中获取一个对象的所有属性的数组?基本上,我想做的是这样的:
Is it possible to get an array of all of an object's properties in Objective C? Basically, what I want to do is something like this:
- (void)save {
NSArray *propertyArray = [self propertyNames];
for (NSString *propertyName in propertyArray) {
[self doSomethingCoolWithValue:[self valueForKey:propertyName]];
}
}
这可能吗?看起来应该是这样,但我不知道我的 propertyNames
应该是什么方法.
Is this possible? It seems like it should be, but I can't figure out what method my propertyNames
up there should be.
推荐答案
我做了更多的挖掘,并在 Objective-C 运行时编程指南.以下是我在原始问题中实现我想要做的事情的方法,大量借鉴 Apple 的示例代码:
I did some more digging, and found what I wanted in the Objective-C Runtime Programming Guide. Here's how I've implemented the what I wanted to do in my original question, drawing heavily from Apple's sample code:
#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]];
}
}
我希望这能帮助其他人寻找一种以编程方式访问对象属性名称的方法.
I hope this will help someone else looking for a way to access the names of an object's properties programatically.
这篇关于在 Objective-C 中获取对象的属性数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!