我有一个继承自 NSManagedObject
的 Parent
模型,以及一个继承自 Parent
的 Child
模型。
这是父级
映射:
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/