【问题标题】:RestKit Identical To-One Mappings on Separate Objects ExceptsRestKit 相同对象上的一对一映射,除了
【发布时间】:2015-09-16 15:33:23
【问题描述】:

我知道我正在做的事情很简单,但我对我在这里做错了什么感到有点困惑。

我试图让 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..."

这意味着我做错了什么。

我已尝试查看所有文档,但我很困惑我如何在两个不同对象上使用相同的键使用相同的对象映射。这是针对FooBar 上的Device 一对一关系。

【问题讨论】:

  • 您是否在某处为同一个类运行了两次代码?哪一行是例外?
  • 当我单步执行代码时,它只对给定的类执行一次。除了[responseMapping addRelationshipMappingWithSourceKeyPath:@"device" mapping: deviceResponseMapping];
  • 值得指出但可能不相关的是FooBar 都是Baz 的子类

标签: objective-c restkit


【解决方案1】:

在我的例子中,我已经在调用之外声明了这个键

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

在代码的另一部分。删除此密钥解决了问题。我正在添加它:

[responseMapping addAttributeMappingsFromDictionary: responseAttributeMappings];

【讨论】:

    猜你喜欢
    • 2012-04-23
    • 1970-01-01
    • 2012-08-18
    • 1970-01-01
    • 1970-01-01
    • 2013-08-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多