Skip to content

Instantly share code, notes, and snippets.

@halsk
Created February 16, 2013 14:13
Show Gist options
  • Save halsk/4967100 to your computer and use it in GitHub Desktop.
Save halsk/4967100 to your computer and use it in GitHub Desktop.
Objective-C で、クラスのプロパティ一覧を取得する ref: http://qiita.com/items/ddeb79803bd097617bab
//
// MMPropertyUtil.h
// MoyaMap
//
// Created by Haruyuki Seki on 2/16/13.
// Copyright (c) 2013 Hacker's Cafe. All rights reserved.
//
#import <Foundation/Foundation.h>
@interface MMPropertyUtil : NSObject
+ (NSDictionary *)classPropsFor:(Class)klass;
@end
//
// MMPropertyUtil.m
// MoyaMap
//
// http://stackoverflow.com/questions/754824/get-an-object-attributes-list-in-objective-c
//
// Created by Haruyuki Seki on 2/16/13.
// Copyright (c) 2013 Hacker's Cafe. All rights reserved.
//
#import "MMPropertyUtil.h"
#import "objc/runtime.h"
@implementation MMPropertyUtil
static const char * getPropertyType(objc_property_t property) {
const char *attributes = property_getAttributes(property);
printf("attributes=%s\n", attributes);
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:
/*
if you want a list of what will be returned for these primitives, search online for
"objective-c" "Property Attribute Description Examples"
apple docs list plenty of examples of what you get for int "i", long "l", unsigned "I", struct, etc.
*/
return (const char *)[[NSData dataWithBytes:(attribute + 1) length:strlen(attribute) - 1] bytes];
}
else if (attribute[0] == 'T' && attribute[1] == '@' && strlen(attribute) == 2) {
// it's an ObjC id type:
return "id";
}
else if (attribute[0] == 'T' && attribute[1] == '@') {
// it's another ObjC object type:
return (const char *)[[NSData dataWithBytes:(attribute + 3) length:strlen(attribute) - 4] bytes];
}
}
return "";
}
+ (NSDictionary *)classPropsFor:(Class)klass
{
if (klass == NULL) {
return nil;
}
NSMutableDictionary *results = [[NSMutableDictionary alloc] init];
unsigned int outCount, i;
objc_property_t *properties = class_copyPropertyList(klass, &outCount);
for (i = 0; i < outCount; i++) {
objc_property_t property = properties[i];
const char *propName = property_getName(property);
if(propName) {
const char *propType = getPropertyType(property);
NSString *propertyName = [NSString stringWithUTF8String:propName];
NSString *propertyType = [NSString stringWithUTF8String:propType];
[results setObject:propertyType forKey:propertyName];
}
}
free(properties);
// returning a copy here to make sure the dictionary is immutable
return [NSDictionary dictionaryWithDictionary:results];
}
@end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment