2013-09-08 2 views
3

cline-server app에서 작업하고 있습니다. 내가 서버에서 응답으로 JSON 개체를 받고 있어요 다음 NSDictionary JSON 변환 해요. 이제 NSDictionary를 사용자 지정 데이터 개체에 매핑해야합니다. 이 그래서 만든 BasicDataObject 클래스 :이있는 NSDictionary에서 초기화 할 수 있도록NSObject를 NSObject 서브 클래스에 매핑

#pragma mark - Inits 

- (id)initWithDictionary:(NSDictionary *)dictionary { 
    self = [super init]; 

    if (self) { 
     [self setValuesForKeysWithDictionary:dictionary]; 
    } 

    return self; 
} 

#pragma mark - Service 

- (id)valueForUndefinedKey:(NSString *)key { 
    NSArray *allKeys = [self allKeys]; 
    id returnObject = nil; 
    BOOL keyFound = NO; 

    for (NSString *propertyName in allKeys) { 
     if ([propertyName isEqualToString:key]) { 
      id object = [self performSelector:NSSelectorFromString(key)]; 

      returnObject = object ? object : [NSNull null]; 
      keyFound = YES; 
      break; 
     } 
    } 

    if (!keyFound) { 
     @throw [NSException exceptionWithName:NSUndefinedKeyException reason:[NSString stringWithFormat:@"key '%@' not found", key] userInfo:nil]; 
    } 

    return returnObject; 
} 

- (void)setValue:(id)value forUndefinedKey:(NSString *)key { 
    NSString *capitalizedString = [key stringByReplacingCharactersInRange:NSMakeRange(0,1) 
                   withString:[[key substringToIndex:1] capitalizedString]]; 
    NSString *setterString = [NSString stringWithFormat:@"set%@:", capitalizedString]; 

    [self performSelector:NSSelectorFromString(setterString) withObject:value]; 
} 

- (void)setNilValueForKey:(NSString *)key { 
    object_setInstanceVariable(self, key.UTF8String, 0); 
} 

- (NSArray *)allKeys { 
    unsigned int propertyCount = 0; 
    objc_property_t *properties = class_copyPropertyList(self.class, &propertyCount); 
    NSMutableArray *propertyNames = [NSMutableArray array]; 

    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]]; 
    } 

    free(properties); 

    return propertyNames; 
} 

각 데이터 객체,이 클래스의 서브 클래스입니다.

- (id)initWithDictionary:(NSDictionary *)dictionary 

그것이 올바른/좋은 방법인가, 또는 좀 더 뭔가를 추가해야합니까 : 일부 데이터 객체의 서브 클래스가 일부 사용자 지정 초기화를 필요로하는 경우 , 나는 무시하고있어 그건?

답변

1

이렇게하는 것이 좋습니다. 필자는 json 키가 내 객체의 속성에 가장 적합한 이름이 거의 없다는 것을 알았으므로 수동으로 본 대부분의 사람들의 코드는 객체의 각 속성을 설정하여 1) 원하는대로 이름을 지정하고 2) 기본 값으로 변환 할 수 있습니다. json 사전은 항상 객체를 포함합니다. 예 : NSNumber -> float)