RestKit对单独对象的一对一映射异常

时间:2015-09-16 15:33:23

标签: objective-c restkit

我知道我所做的事情很简单,而且我对这里的错误感到有些困惑。

我试图让JSON对象上的给定键始终映射到同一个Objective-C类。此密钥在具有它的所有JSON对象上具有相同的名称(device)。

我有两个类FooBar,每个类都有一个device属性:

@interface Foo
@property (strong, nonatomic) Device * device;
@end

@interface Bar
@property (strong, nonatomic) Device * device;
@end

@interface Device
@property (strong, nonatomic) NSString * deviceId;
@property (strong, nonatomic) NSString * deviceName;
@end

对于我的服务器为FooBar发送的JSON,设备的表示如下:

{
    "device": {
        "deviceId": "someId",
        "deviceName": "someName"
    }
}

在我的应用程序中RestKit的配置函数中,我有以下内容:

RKObjectMapping * responseMapping = [RKObjectMapping mappingForClass: model[@"class"]];

if ( model[@"class"] == [Foo class] ||
     model[@"class"] == [Bar class] ){

    NSArray * defaultRequestKeys = @[@"id", @"createdAt", @"updatedAt"];
    NSArray * defaultModelKeys = @[@"objectId", @"createdAt", @"updatedAt"];
    NSArray * deviceRequestKeys = [@[@"deviceName", @"deviceId"] arrayByAddingObjectsFromArray: defaultRequestKeys];
    NSArray * deviceModelKeys = [@[@"deviceName", @"deviceId"] arrayByAddingObjectsFromArray: defaultModelKeys];

    RKObjectMapping * deviceResponseMapping;

    deviceResponseMapping = [RKObjectMapping mappingForClass: [Device class]];
    [deviceResponseMapping addAttributeMappingsFromDictionary: [NSDictionary dictionaryWithObjects: deviceModelKeys
                                                                                           forKeys: deviceRequestKeys]];

    [responseMapping addRelationshipMappingWithSourceKeyPath:@"device" mapping: deviceResponseMapping];

}

但是,RestKit除了failed: caught "NSInternalInconsistencyException", "Unable to add mapping for keyPath device, one already exists..."

这意味着我做错了什么。

我已经尝试查看整个文档了,我很困惑我在两个不同的对象上使用相同的对象映射。这适用于DeviceFoo上的Bar对一关系。

1 个答案:

答案 0 :(得分:0)

在我的情况下,我已经在

的调用之外声明了这个键
[responseMapping addRelationshipMappingWithSourceKeyPath:@"device" mapping: deviceResponseMapping];

代码的另一部分。删除此键修复了问题。我正在添加它:

[responseMapping addAttributeMappingsFromDictionary: responseAttributeMappings];