RestKit直接+反向关系映射

时间:2014-08-26 09:38:12

标签: core-data restkit

作为新手RestKit用户,我对CoreData关系映射有一个概念性的理解问题。

假设我们有一个CoreData模型,只有两个主/细节关系的实体:

@interface Master : NSManagedObject
@property (nonatomic, retain) NSString *objectId;
@property (nonatomic, retain) NSString *display;
@property (nonatomic, retain) NSSet *childrens;
@end

@interface Children : NSManagedObject
@property (nonatomic, retain) NSString *objectId;
@property (nonatomic, retain) NSString *display;
@property (nonatomic, retain) Master *father;
@end

此模型的RestKit映射是:

RKEntityMapping *masterMapping = ...
RKEntityMapping *childrenMapping = ...

... property mappings ...

masterMapping.identificationAttributes = @[ @"objectId" ];
childrenMapping.identificationAttributes = @[ @"objectId" ];

[masterMapping addPropertyMapping:[RKRelationshipMapping  
  relationshipMappingFromKeyPath:@"childrens" toKeyPath:@"childrens"
  withMapping:childrensMapping]];

[childrenMapping addPropertyMapping:[RKRelationshipMapping  
  relationshipMappingFromKeyPath:@"father" toKeyPath:@"father"
  withMapping:masterMapping]];

以下是如何建模http获取响应(我可以更改它):

{
 objectId: "3",
 display: "a master object",
 childrens: [
   {
     objectId: "1",
     display: "a child object",
     father: { objectId: "3" }
   },
   {
     objectId: "2",
     display: "another child object",
     father: { objectId: "3" }
   }
 ]

}

问题是,在将RestKit与某些RKResponseDescriptor相关联时,先前的映射定义会导致RestKit出现循环映射错误。

我已经阅读了RestKit文档和许多stackoverflow.com类似的线程,但我仍然不明白如何设置完整的 CoreData模型关系映射,前提是我需要有两个关系在我的代码中可用(即我需要明确地访问来自孩子的父亲和来自主实体的孩子)。

任何帮助将不胜感激。

非常感谢提前!

1 个答案:

答案 0 :(得分:0)

我自己想出了我的映射理解问题,并且我想分享一下以防万一:RestKit模型映射并不意味着在模型中定义"绝对& #34;条款,但相对"对模型的RESTful操作。

换句话说,模型实体可以有多个RestKit映射,每个映射对应于在GET / POST / PATCH /等中引用该实体的方式。操作

我希望这可以帮助其他人轻松理解RestKit漂亮的框架!