Skip to content

Instantly share code, notes, and snippets.

@shu223
Last active February 12, 2018 18:12
Show Gist options
  • Save shu223/1913148 to your computer and use it in GitHub Desktop.
Save shu223/1913148 to your computer and use it in GitHub Desktop.
オブジェクトが持つプロパティの型と名前のリストを取得する ref: http://qiita.com/items/2823
#import "objc/runtime.h"
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] != '@') {
            return (const char *)[[NSData dataWithBytes:(attribute + 1) length:strlen(attribute) - 1] bytes];
        }        
        else if (attribute[0] == 'T' && attribute[1] == '@' && strlen(attribute) == 2) {
            return "id";
        }
        else if (attribute[0] == 'T' && attribute[1] == '@') {
            return (const char *)[[NSData dataWithBytes:(attribute + 3) length:strlen(attribute) - 4] bytes];
        }
    }
    return "";
}
- (NSDictionary *)properties {
    unsigned int outCount, i;
    objc_property_t *props = class_copyPropertyList([self class], &outCount);
    NSMutableDictionary *dic = [NSMutableDictionary dictionaryWithCapacity:0];
    for(i = 0; i < outCount; i++) {
        objc_property_t property = props[i];
        const char *propName = property_getName(property);
        if(propName) {
            const char *propType = getPropertyType(property);
            NSString *propertyName = [NSString stringWithCString:propName];
            NSString *propertyType = [NSString stringWithCString:propType];
            [dic setObject:propertyType forKey:propertyName];
        }
    }
    free(props);

    return dic;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment