Get an object attributes list in Objective-C


- (void)getPropertyList:(id)object {

    u_int count, i;

    objc_property_t *properties = class_copyPropertyList([object class], &count);

    for(i = 0; i < count; i++) {

        objc_property_t property = properties[i];

        const char *propName = property_getName(property);

        if(propName) {

            const char *propType = getPropertyType(property);

            NSString *propertyType = [NSString stringWithCString:propType

                                                        encoding:[NSString defaultCStringEncoding]];

            

            NSString *propertyName = [NSString stringWithCString:propName

                                                        encoding:[NSString defaultCStringEncoding]];

            id propertyDefaultValue = [object valueForKey:propertyName];

            NSLog(@"%@_%@:%@\n\n",propertyType,propertyName,propertyDefaultValue);

        }

    }

    free(properties);

}


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') {

            return (const char *)[[NSData dataWithBytes:(attribute + 1) length:strlen(attribute) - 1] bytes];

        }

    }

    return "id";

}


你可能感兴趣的:(Objective-C)