3

我正在开发 cline-server 应用程序。我从服务器获取 JSON 对象作为响应,然后将 JSON 转换为 NSDictionary。现在我需要将 NSDictionary 映射到自定义数据对象。所以我创建了 BasicDataObject 类,它具有:

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

每个数据对象都是这个类的一个子类,所以它可以从 NSDictionary 初始化。如果某些数据对象子类需要一些自定义初始化,我将覆盖它:

- (id)initWithDictionary:(NSDictionary *)dictionary

这是正确/好的方法,还是我需要添加更多内容?

4

1 回答 1

2

这是一个很好的方法来做到这一点。我发现 json 键很少是我的对象属性的最合适的名称,所以我见过的大多数人的代码手动设置对象上的每个属性,以便他们可以 1)将其命名为他们想要的任何名称 2)转换为原始值json 字典,它将始终包含对象。(例如 NSNumber -> 浮点数)

于 2013-09-08T13:35:15.790 回答