iOS获取属性类 [英] iOS get property class
问题描述
我正在尝试获取未知类的所有属性列表以及每个属性的类。到目前为止,我得到了一个对象的所有属性的列表(我递归地获取所有的超类)。我启发了这篇文章
I'm trying to get a list of all the properties of an unknown class and the class of every property. By the moment I get a list of all the properties of an object(I do it recursively to get all of the superclasses). I inspired in this post
+ (NSArray *)classPropsFor:(Class)klass
{
NSLog(@"Properties for class:%@", klass);
if (klass == NULL || klass == [NSObject class]) {
return nil;
}
NSMutableArray *results = [[NSMutableArray alloc] init];
unsigned int outCount, i;
objc_property_t *properties = class_copyPropertyList(klass, &outCount);
for (i = 0; i < outCount; i++) {
objc_property_t property = properties[i];
const char *propName = property_getName(property);
if(propName) {
NSString *propertyName = [NSString stringWithUTF8String:propName];
[results addObject:propertyName];
}
NSArray* dict = [self classPropsFor:[klass superclass]];
[results addObjectsFromArray:dict];
}
free(properties);
return [NSArray arrayWithArray:results];
}
所以现在我想要每个属性的类,我这样做:
So now I want the class of every property and I do:
NSArray* properties = [PropertyUtil classPropsFor:[self class]];
for (NSString* property in properties) {
id value= [self valueForKey:property];
NSLog(@"Value class for key: %@ is %@", property, [value class]);
}
问题是它适用于NSStrings,但不适用于自定义类,它返回null。我想递归地创建一个字典来表示一个对象,里面可以有其他对象,因为我认为我需要知道每个属性的类,这可能吗?
The problem is it works for NSStrings or but not for custom classes, for that it returns me null. I want to recursively create a dictionary that represents an object that can have other objects inside and as I thinks I need to know the class of every property, is that possible?
推荐答案
您应该在存储 propertyName
的同时为每个属性存储类(作为字符串)。也许作为一个字典,其属性名称为键,类名称为值,反之亦然。
You should probably store the class (as a string) for each property at the same time as you store the propertyName
. Maybe as a dictionary with property name as the key and class name as the value, or vice versa.
要获取类名,可以执行以下操作(put这是在你声明 propertyName
)之后:
To get the class name, you can do something like this (put this right after you declare propertyName
):
NSString* propertyAttributes = [NSString stringWithUTF8String:property_getAttributes(property)];
NSArray* splitPropertyAttributes = [propertyAttributes componentsSeparatedByString:@"\""];
if ([splitPropertyAttributes count] >= 2)
{
NSLog(@"Class of property: %@", [splitPropertyAttributes objectAtIndex:1]);
}
字符串处理代码是因为属性包含许多信息 - 具体细节在此处指定: https://developer.apple.com/library/mac/#documentation/Cocoa/Conceptual/ObjCRuntimeGuide/Articles/ocrtPropertyIntrospection.html
The string handling code is because the attributes include a number of pieces of information - the exact details are specified here: https://developer.apple.com/library/mac/#documentation/Cocoa/Conceptual/ObjCRuntimeGuide/Articles/ocrtPropertyIntrospection.html
这篇关于iOS获取属性类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!