【问题标题】:Restkit - Child mapping doesn't inherit its parent mapping?Restkit - 子映射不继承其父映射?
【发布时间】:2012-07-19 10:08:28
【问题描述】:

我有一个继承自 NSManagedObjectParent 模型和一个继承自 ParentChild 模型。

这是Parent 映射:

RKManagedObjectStore* store = [RKObjectManager sharedManager].objectStore;
RKManagedObjectMapping* mapping = [RKManagedObjectMapping mappingForEntityWithName:@"Parent" inManagedObjectStore:store];
[mapping mapKeyPath:@"id" toAttribute:@"id"];
[[RKObjectManager sharedManager].mappingProvider addObjectMapping:mapping];

还有Child 映射:

RKManagedObjectStore* store = [RKObjectManager sharedManager].objectStore;
RKManagedObjectMapping* mapping = [RKManagedObjectMapping mappingForEntityWithName:@"Child" inManagedObjectStore:store];
[[RKObjectManager sharedManager].mappingProvider setMapping:mapping forKeyPath:@"child"];

然后,当我尝试将以下 JSON 对象映射到 Child 实例时:

{
  "child": {
    "id": 7
  }
}

在 RestKit 跟踪中,我看到 Child 的以下映射:

mappings => ()

为什么Child 映射不继承自Parent 映射?如何使映射继承起作用?

【问题讨论】:

    标签: objective-c core-data inheritance mapping restkit


    【解决方案1】:

    简而言之,它不起作用,因为 RestKit 不支持它,我认为不应该。

    如果您希望子映射具有父映射,您也可以将其添加到子映射中,如果您独立编写它们,这是一行额外的代码,或者如果您使用 @,则只需几个额外的字符987654321@ 方法。

    关于您的具体示例,有一点很重要。一是你不应该使用 'id' 作为你的属性名称,因为 id 在 ObjC 中是保留的(我不肯定它实际上会导致问题,但至少在代码中看到它会令人困惑)。

    因此,RestKit 中有一个标准约定来映射“id”属性,即将实体的名称添加到属性之前,即Parent 将具有 parentID 属性,Child 将具有childID 财产。仅此一点就说明了为什么在一般情况下继承这些属性(尤其是主键!)不是一个好主意。

    此外,RESTful 服务器通常有某种基于 SQL 的后端,它可能支持也可能不支持 Core Data 所具有的实体继承类型,从而使对象从设备映射到数据的方式复杂化服务器。例如,Rails 可以在一定程度上处理 STI,但任何比这更复杂的东西都需要 gems 或 hacks。

    编辑:(取自 github 问题) 如果有人发现这是在寻找一种继承方式,那么有一种相对简单的方法可以基于其他映射创建映射:

    RKManagedObjectMapping* parentMapping = [RKManagedObjectMapping mappingForEntityWithName:@"Child" inManagedObjectStore:store];
    parentMapping.primaryKeyAttribute = @"parentID";
    [parentMapping mapKeyPathsToAttributes: @"id", @"parentID", @"property_one", @"propertyOne", @"parent_only_property", @"parentOnlyProperty"];
    [[RKObjectManager sharedManager].mappingProvider setMapping:mapping forKeyPath:@"parent"];
    
    RKManagedObjectMapping* childMapping = [parentMapping copy];
    childMapping.primaryKeyAttribute = @"childID";
    [childMapping removeMapping:[childMapping mappingForAttribute:@"parentID"]];
    [childMapping removeMapping:[childMapping mappingForAttribute:@"parentOnlyProperty"];
    [childMapping mapKeyPathsToAttributes:@"id", @"childID", @"child_only_property", @"childOnlyProperty"];
    [[RKObjectManager sharedManager].mappingProvider setMapping:childMapping forKeyPath:@"child"];
    

    【讨论】:

    • 您清楚地解释了为什么让孩子继承其父映射没有意义。谢谢 ! ;)
    猜你喜欢
    • 1970-01-01
    • 2012-05-25
    • 2012-03-20
    • 1970-01-01
    • 2017-12-07
    • 2011-11-22
    • 2010-11-25
    • 1970-01-01
    相关资源
    最近更新 更多