检测在objective-c中具有名称的属性的类

时间:2014-02-25 15:24:42

标签: ios objective-c introspection

我在运行时在objective-c中有一个NSObject,我想知道这个对象中属性的类,我将这个属性的名称作为NSString,我该怎么做。

编辑

IntrospectionUtility类:

     @implementation IntrospectionUtility

        // this function returns an array of names of properties 


+ (NSMutableArray*) getProperties:(Class)class
    {
        NSMutableArray *properties = [[NSMutableArray alloc] init];
        unsigned int outCount, i;
        objc_property_t *objc_properties = class_copyPropertyList(class, &outCount);
        for(i = 0; i < outCount; i++) {
            objc_property_t property = objc_properties[i];
            const char *propName = property_getName(property);
            if(propName) {
                NSString *propertyName = [NSString stringWithCString:propName encoding:[NSString defaultCStringEncoding]];
                [properties addObject:propertyName];
            }
        }
        free(objc_properties);
        return properties;
    }

    @end

班级考试:

@interface JustAnExample : NSObject

@property (nonatomic, strong) NSString *a;
@property (nonatomic, strong) NSString *b;
@property (nonatomic, strong) NSString *c;
@property (nonatomic, strong) NSString *d;

@end



@implementation JustAnExample


 - (void) justAnExampleTest
 {
     NSMutableArray *attributes = [IntrospectionUtility getProperties:self.class];
    for (NSString *attribute in attributes) {
       //i want to know the type of each attributte
    }

 }

@end

1 个答案:

答案 0 :(得分:2)

  

我将此属性的名称作为NSString

您可以使用函数class_getProperty(Class cls, const char *name)查找给定类的属性。然后使用property_getAttributes(objc_property_t property)获取属性的属性,包括编码的类型字符串。阅读 Objective-C运行时编程指南Declared Properties部分以获取更多信息。