6

我正在尝试获取未知类的所有属性和每个属性的类的列表。到那时我得到一个对象所有属性的列表(我递归地做它以获取所有超类)。我在这篇文章中受到启发

+ (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]);
}

问题是它适用于 NSStrings 或但不适用于自定义类,因为它返回我为 null。我想递归地创建一个字典,该字典表示一个可以在其中包含其他对象的对象,并且我认为我需要知道每个属性的类,这可能吗?

4

4 回答 4

7

刚刚为此做了一个小方法。

// Simple as.
Class propertyClass = [customObject classOfPropertyNamed:propertyName];

可以在很多方面进行优化,但我喜欢它。


实现如下:

-(Class)classOfPropertyNamed:(NSString*) propertyName
{
    // Get Class of property to be populated.
    Class propertyClass = nil;
    objc_property_t property = class_getProperty([self class], [propertyName UTF8String]);
    NSString *propertyAttributes = [NSString stringWithCString:property_getAttributes(property) encoding:NSUTF8StringEncoding];
    NSArray *splitPropertyAttributes = [propertyAttributes componentsSeparatedByString:@","];
    if (splitPropertyAttributes.count > 0)
    {
        // xcdoc://ios//library/prerelease/ios/documentation/Cocoa/Conceptual/ObjCRuntimeGuide/Articles/ocrtPropertyIntrospection.html
        NSString *encodeType = splitPropertyAttributes[0];
        NSArray *splitEncodeType = [encodeType componentsSeparatedByString:@"\""];
        NSString *className = splitEncodeType[1];
        propertyClass = NSClassFromString(className);
    }
    return propertyClass;
}

它是eppz!kit的一部分,在一个名为NSObject+EPPZRepresentable.h. 它实际上完成了您最初要实现的目标。

// Works vica-versa.
NSDictionary *representation = [customObject dictionaryRepresentation];
CustomClass = [CustomClass representableWithDictionaryRepresentation:representation];

它编码许多类型,迭代槽集合,表示 CoreGraphics 类型,UIColors,还表示/重构对象引用。


新版本甚至会吐出C 类型名称命名结构类型

NSLog(@"%@", [self typeOfPropertyNamed:@"index"]); // unsigned int
NSLog(@"%@", [self typeOfPropertyNamed:@"area"]); // CGRect
NSLog(@"%@", [self typeOfPropertyNamed:@"keyColor"]); // UIColor

eppz !model的一部分,请随时在https://github.com/eppz/eppz.model/blob/master/eppz!model/NSObject%2BEPPZModel_inspecting.m#L111使用方法实现

于 2014-01-16T16:12:08.957 回答
2

更新

这不适用于nil. 相反,您应该使用运行时 C API 从相应的 ivar 或访问器方法获取类。

于 2012-05-21T14:53:04.880 回答
2

您可能应该在存储propertyName. 也许作为一个字典,属性名作为键,类名作为值,反之亦然。

要获取类名,您可以执行以下操作(在您声明后立即输入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

于 2012-05-21T15:01:36.693 回答
0

添加到 NSObject 类别的以下内容可以解决问题。

- (Class) classForKeyPath:(NSString*)keyPath {
    Class class = 0;

    unsigned int n = 0;
    objc_property_t* properties = class_copyPropertyList(self.class, &n);
    for (unsigned int i=0; i<n; i++) {
        objc_property_t* property = properties + i;
        NSString* name = [NSString stringWithCString:property_getName(*property) encoding:NSUTF8StringEncoding];
        if (![keyPath isEqualToString:name]) continue;

        const char* attributes = property_getAttributes(*property);
        if (attributes[1] == '@') {
            NSMutableString* className = [NSMutableString new];
            for (int j=3; attributes[j] && attributes[j]!='"'; j++)
                [className appendFormat:@"%c", attributes[j]];
            class = NSClassFromString(className);
        }
        break;
    }
    free(properties);

    return class;
}
于 2016-02-24T19:17:33.103 回答