objective-c - Restkit - 子映射不继承其父映射?

标签 objective-c core-data inheritance mapping restkit

我有一个继承自 NSManagedObjectParent 模型,以及一个继承自 ParentChild 模型。

这是父级映射:

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

以及映射:

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映射?如何使映射继承起作用?

最佳答案

简而言之,它不起作用,因为 RestKit 不支持它,而且在我看来也不应该支持。

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

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

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

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

编辑:(取自 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"];

关于objective-c - Restkit - 子映射不继承其父映射?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11558512/

相关文章:

ios - 从另一个 View 删除现有数据

c++ - 当我在基类中设置 protected 数据时,它会更改派生类中 protected 数据的值吗?

ios - 如何在 iOS 中使用 Metal API 中的计算函数进行乘法

iOS : Repositioning UIGraphicsBeginImageContext and UIImageView

iphone - 了解 Core Data 中的嵌套上下文

c# - MVC View 继承

scala - Scala 对象定义中没有父类(super class)名称的 "extends {..}"子句有什么作用?

objective-c - 调用 objc 静态库的 swift 应用程序出现链接错误

ios - 如何在 Collection View 中给 UILabel 一个闪烁的效果

swift - 合并不同上下文的数据,自动MergesChangesFromParent用法