본문 바로가기

Project

JSON data로부터 간단히 모델 클래스를 구현하기


코어데이터는 데이터를 다루기 위한 굉장히 편리한 도구이지만 데이터의 영속성이 필요하지 않은 경우에는

일부러 코어데이터를 쓰지 않아도 간단히 데이터 모델을 구현할 방법은 많이 있다.


모델클래스를 작성하고 JSON Data로부터 해당 데이터를 바인딩시키는 간단한 코드를 소개한다.

먼저 모델클래스이다.

보다시피 프로퍼티와 초기화 메소드를 하나 지정해둔다.


@interface User : NSObject


@property (nonatomic,strong) NSString *userId;

@property (nonatomic,strong) NSString *userName;

@property (nonatomic,strong) NSNumber *age;

@property (nonatomic,strong) NSString *imagePath;


-(id)initWithDictionary:(NSDictionary *)aDict;


@end

NSObject의 카테고리클래스중 하나인 NSKeyValueCoding은 유용한 메소드를 많이 가지고 있는데

그중 setValuesForKeysWithDictionary: 을 이용하면 dictionary로부터 자동으로 property값들을 세팅할수가 있다.

조심해야할 부분은 이름이 다르거나 가지고 있지 않은 프로퍼티일경우 예외를 내기 때문에

valueForUndefinedKey과 setValue: forUndefinedKey: 를 구현해두어야한다.

#import "User.h"


@implementation User

@synthesize userId,userName,age,imagePath;


-(id)initWithDictionary:(NSDictionary *)aDict

{

    self = [self init];

    if (self != nil) {

        if (aDict) {

            [self setValuesForKeysWithDictionary:aDict];

        }

    }

    return self;

}


- (id)valueForUndefinedKey:(NSString *)key

{

    NSLog(@"undefined key : %@",key);

    return  nil;

}


-(void)setValue:(id)value forUndefinedKey:(NSString *)key

{

    NSLog(@"undefined key : %@",key);

}


-(NSString *)description

{

    NSString *desc = @"";

    for (NSString *key in [PropertyUtil propertyNames:[self class]]) {

        desc = [desc stringByAppendingFormat:@"%@ : %@ ,",key,[self valueForKey:key]];

    }

    return desc;

}


@end

데이터초기화는 아래 한줄이면 된다.

User *user =  [[User alloc] initWithDictionary:jsonValue];



너무 간단한 코드들이라 특별히 이해하는데는 어렵지 않을듯하다.



p.s

직접구현한 모델일경우 프로퍼티내용을 description으로 표시하기가 귀찮을경우가 많은데 아래의 코드를 이용하면 클래스로부터 프로퍼티 이름을 배열로 받을수 있다.

#import <objc/runtime.h>

+ (NSArray *) propertyNames: (Class) class

    NSMutableArray *propertyNames = [[NSMutableArray alloc] init];

    unsigned int propertyCount = 0;

    objc_property_t *properties = class_copyPropertyList(class, &propertyCount);

    

    for (unsigned int i = 0; i < propertyCount; ++i) {

        objc_property_t property = properties[i];

        const char * name = property_getName(property);

        [propertyNames addObject:[NSString stringWithUTF8String:name]];

    }


    return [propertyNames copy];

}