hachinoBlog

hachinobuのエンジニアライフ

自作クラスのプロパティ変数名一覧を取得する方法

JSONデータを扱う際にJSONデータと同じキーのプロパティ変数を持つ自作クラスを作成してJSONデータをパースして保存することがよくある。
その際に自作クラスのプロパティ変数がJSONデータのキー値となるので、プロパティ変数名の一覧が取れると便利。

やり方は下記の通り

Person.h

@interface Person : NSObject

@property (nonatomic, strong) NSString *firstName;
@property (nonatomic, strong) NSString *lastName;
@property (nonatomic, strong) NSNumber *age;
@property (nonatomic, strong) NSDate *since;

- (NSArray *)properties;

@end

Person.m

#import "SampleModel.h"
#import "objc/runtime.h"

@implementation Person

- (NSArray *)properties
{
    
    NSMutableArray *results = [NSMutableArray array];
    
    unsigned int outCount, i;
    objc_property_t *properties = class_copyPropertyList([self class], &outCount);
    for (i = 0; i < outCount; i++) {
        objc_property_t property = properties[i];
        const char *propName = property_getName(property);
        if(propName) {
            NSString *propertyName = [NSString stringWithUTF8String:propName];
            [results addObject:propertyName];
        }
    }
    free(properties);
    
    return [results copy];
    
}

@end

使う側

Person *person = [[Person alloc] init];
NSLog(@"results:%@", [person properties]);

出力結果
results:(
firstName,
lastName,
age,
since
)


propertiesメソッドを実装するスーパークラスを作成してあげて自作クラスは、そのクラスを継承してあげることで全ての自作クラスから汎用的に使えますね。

- (NSArray *)properties:(Class)kclass
{
    
    NSMutableArray *results = [NSMutableArray array];
    
    unsigned int outCount, i;
    objc_property_t *properties = class_copyPropertyList([kclass class], &outCount);
    for (i = 0; i < outCount; i++) {
        objc_property_t property = properties[i];
        const char *propName = property_getName(property);
        if(propName) {
            NSString *propertyName = [NSString stringWithUTF8String:propName];
            [results addObject:propertyName];
        }
    }
    free(properties);
    
    return [results copy];
    
}

ちなみにプロパティの変数名だけでなく型も取得できるようです。
参考URL
http://d.hatena.ne.jp/shu223/20120226/1330231240
https://github.com/omergul123/LLModel