我想獲得一個未知類的所有屬性和每個屬性的類的列表。到目前爲止,我得到一個對象的所有屬性的列表(我遞歸獲取所有的超類)。我在this postiOS獲取房產類
+ (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];
}
啓發所以現在我希望類的每個屬性的,我做的事:
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]);
}
問題是,它適用於NSString的或而不是自定義類,對於它返回我空值。我想遞歸地創建一個代表一個可以有其他對象的對象的字典,因爲我認爲我需要知道每個屬性的類,這是可能的嗎?
真棒,完美的作品!感謝您的幫助:) – Jpellat
不客氣:) –