RestKit - 实体映射属性转换

时间:2013-05-27 09:53:07

标签: objective-c core-data restkit

我需要使用小写的对象属性映射一个带有对象属性的Web服务,所有这些都是小写的:

# JSON
{
    'ID': 'value',
    'TITLE': 'value',
    'BODY': 'value',
}
# CoreData Entity
{
    'id': 'value',
    'title': 'value',
    'body': 'value',
}

我通过执行以下方式映射字段:

RKEntityMapping *entMap = [RKEntityMapping mappingForEntityForName:entName 
    inManagedObjectStore:managedObjectStore];
NSEntityDescription *entity = [[managedObjectModel entitiesByName] 
    objectForKey:entName];
[entMap addAttributeMappingsFromArray:[[[RKPropertyInspector sharedInspector]
    propertyInspectionForEntity:entity] allKeys]];

我在setDefaultSourceToDestinationKeyTransformationBlock中看到了这个方便的RKObjectMapping功能,允许在对象属性上定义自定义转换。这不适用于RKEntityMapping

如何在不定义字段的情况下使用RKEntityMapping进行属性转换?

1 个答案:

答案 0 :(得分:0)

以下是我目前的解决方法:

- (NSDictionary *)dictToArray:(NSArray *)array
    withTranformation:(NSString *(^)(NSString *))theBlock
{
    NSMutableDictionary *dict = [[NSMutableDictionary alloc] init];
    for (NSString *key in array) {
        dict[theBlock(key)] = key;
    }
    return dict;
}

NSArray *fields = [[[RKPropertyInspector sharedInspector] 
    propertyInspectionForEntity:entity] allKeys];
NSDictionary *mapDict = [self dictToArray:fields
    withTranformation:^NSString *(NSString *str) {
        return [str uppercaseString];
    }];

[entMap addAttributeMappingsFromDictionary:mapDict];