Thursday 25 July 2013

How to Get a List of all Properties that are declared in an Interface or Class in Objective C at RunTime:


-(NSArray*)listAllPropertiesInClassName:(NSString *)className
{
    Class classRef = NSClassFromString(className);
    
    unsigned int propCount;
    
    objc_property_t  *properties = class_copyPropertyList(classRef, &propCount);
    NSMutableArray *arr = [NSMutableArray array];
    for (int i=0; i < propCount; i++)
    {
        objc_property_t property = properties[i];
        
        //Get Property Name
        const char *propertyName = property_getName(property);
        if(propertyName)
        {
            //Get property Type
            const char *propertyType = getPropertyType(property);
            
            NSString *propName = [NSString stringWithUTF8String:propertyName];
            NSString *propType = [NSString stringWithUTF8String:propertyType];
            NSLog(@"%@==%@", propName, propType);
            NSDictionary *dic = [NSDictionary dictionaryWithObjectsAndKeys:propName,  @"ProperyName", propType, @"PropertyType",nil];                                

            [arr addObject:dic];
        }
    }
    
    return (NSArray*)arr;
}


static const char *getPropertyType(objc_property_t property)
{
    const char *attributes = property_getAttributes(property);
    char buffer[1 + strlen(attributes)];
    strcpy(buffer, attributes);
    char *state = buffer, *attribute;
    while ((attribute = strsep(&state, ",")) != NULL) {
        if (attribute[0] == 'T' && attribute[1] != '@') {
            // it's a C primitive type:
            /*
               you will get "i", "l", "I", struct, etc.
              for int "i", long "l", unsigned "I", struct, etc.
             */
            NSString *name = [[NSString alloc] initWithBytes:attribute + 1 length:strlen(attribute) - 1 encoding:NSASCIIStringEncoding];
            return (const char *)[name cStringUsingEncoding:NSASCIIStringEncoding];
        }
        else if (attribute[0] == 'T' && attribute[1] == '@' && strlen(attribute) == 2) {
            // It is an Objective-C id Type object
            return "id";
        }
        else if (attribute[0] == 'T' && attribute[1] == '@') {
            // Its anothoer Objective C Type Object:
            NSString *name = [[NSString alloc] initWithBytes:attribute + 3 length:strlen(attribute) - 4 encoding:NSASCIIStringEncoding];
            return (const char *)[name cStringUsingEncoding:NSASCIIStringEncoding];
        }
    }
    return "";
}













No comments:

Post a Comment