如何在 Objective-C 中获取给定对象属性的列表(以 NSArray
或 NSDictionary
的形式)?
想象以下场景:我定义了一个父类,它只是扩展了 NSObject
,它包含一个 NSString
、一个 BOOL
和一个 NSData
对象作为属性。然后我有几个类扩展了这个父类,每个类都添加了很多不同的属性。
有没有什么办法可以在 parent 类上实现一个实例方法,该方法遍历整个对象并返回,例如,每个(child)的 NSArray
) 作为 NSStrings
的类属性在父类上 not,所以我以后可以将这些 NSString
用于 KVC?
最佳答案
我自己设法得到了答案。通过使用 Obj-C 运行时库,我可以按照我想要的方式访问属性:
- (void)myMethod {
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 stringWithCString:propName
encoding:[NSString defaultCStringEncoding]];
NSString *propertyType = [NSString stringWithCString:propType
encoding:[NSString defaultCStringEncoding]];
...
}
}
free(properties);
}
这需要我制作一个“getPropertyType”C 函数,该函数主要取自 Apple 代码示例(现在不记得确切的来源):
static const char *getPropertyType(objc_property_t property) {
const char *attributes = property_getAttributes(property);
char buffer[1 + strlen(attributes)];
strcpy(buffer, attributes);
char *state = buffer, *attribute;
while ((attribute = strsep(&state, ",")) != NULL) {
if (attribute[0] == 'T') {
if (strlen(attribute) <= 4) {
break;
}
return (const char *)[[NSData dataWithBytes:(attribute + 3) length:strlen(attribute) - 4] bytes];
}
}
return "@";
}
https://stackoverflow.com/questions/754824/