Search code examples
iosobjective-cintrospection

detect the class of a property with name in objective-c


I have an NSObject in objective-c at runtime and i want to know the class of a property in this object , i have the name of this property as NSString , how can I do that.

EDIT :

IntrospectionUtility class :

     @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

class test :

@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

Solution

  • i have the name of this property as NSString

    You can use the function class_getProperty(Class cls, const char *name) to find the property for a given class. Then use property_getAttributes(objc_property_t property) to get the property's attributes, including the encoded type string. Read the Declared Properties section of the Objective-C Runtime Programming Guide for more info.