【问题标题】:Mapping NSDictionary to NSObject subclass将 NSDictionary 映射到 NSObject 子类
【发布时间】:2013-09-12 02:33:51
【问题描述】:

我正在开发 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

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

【问题讨论】:

    标签: ios objective-c networking nsdictionary kvc


    【解决方案1】:

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

    【讨论】:

      猜你喜欢
      • 2014-05-16
      • 1970-01-01
      • 2020-07-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-01-17
      相关资源
      最近更新 更多