寻求针对浅层路由的最佳RestKit / CoreData映射和JSON结构的建议
我正在开发一个由(Rails)REST API(支持浅层路由)支持的CoreData iOS应用程序。 因为图中有很多对象,所以我希望REST GET不包含大量嵌套结果,而只是包含RestKit用于建立(故障)关系的引用。 然后,我将根据需要使用浅路由来请求单个(或一组)对象。
假设我有一对多(>)数据模型,如A > B,我有:
RKEntityMapping *a_mapping = [RKEntityMapping mappingForEntityForName:@"A" inManagedObjectStore:managedObjectStore]; [a_mapping addAttributeMappingsFromDictionary:@{@"a_id" : @"aId", ...}]; a_mapping.identificationAttributes = @[@"aId"]; RKEntityMapping *b_mapping = [RKEntityMapping mappingForEntityForName:@"B" inManagedObjectStore:managedObjectStore]; [b_mapping addAttributeMappingsFromDictionary:@{@"b_id" : @"bId", ...}]; b_mapping.identificationAttributes = @[@"bId"]; [a_mapping addPropertyMapping:[RKRelationshipMapping relationshipMappingFromKeyPath:@"bs" toKeyPath:@"bs" withMapping:b_mapping]];
我有这些路线:
NSIndexSet *statusCodes = RKStatusCodeIndexSetForClass(RKStatusCodeClassSuccessful); RKResponseDescriptor *a_ResponseDescriptor; a_ResponseDescriptor = [RKResponseDescriptor responseDescriptorWithMapping:a_mapping method:RKRequestMethodGET pathPattern:@"/A/:aId" keyPath:@"A" statusCodes:statusCodes]; RKResponseDescriptor *b_ResponseDescriptor; NSIndexSet *statusCodes = RKStatusCodeIndexSetForClass(RKStatusCodeClassSuccessful); b_ResponseDescriptor = [RKResponseDescriptor responseDescriptorWithMapping:b_mapping method:RKRequestMethodGET pathPattern:@"/B/:bId" keyPath:@"B" statusCodes:statusCodes]; [[RKObjectManager sharedManager] addResponseDescriptor:a_ResponseDescriptor]; [[RKObjectManager sharedManager] addResponseDescriptor:b_ResponseDescriptor];
我有几个相关的问题:
-
返回“A”记录时,我应该如何构造JSON,以便RestKit将为任何相关的“B”对象实例化存根?
-
类似地,如果我想请求一堆B对象(没有A对象的先验知识),如何在返回’B’记录时构造JSON,以便RestKit将为拥有的’A’对象实例化存根?
-
RestKit需要哪些额外的设置/代码?
目前,我有一个方向工作(A – > B),但我似乎无法弄清楚如何使反向工作。 特别是/A/1.json返回类似于:
{"a": {"a_id":1, "bs":[{"b_id": 2}, {"b_id": 3}]}}
并且B / 2.json返回:
{"b": {"b_id":2, "a_id": 1}}
我应该使用类似的东西:
{"b": {"b_id":2, "a": {"a_id": 1}}}
? 任何帮助/建议将不胜感激。
故障是核心数据概念。 RestKit涉及在数据存储中创建对象,但它是从数据存储中获取它们的行为,这会对它们造成错误。 听起来更像是你感兴趣的是让RestKit在数据存储中创建’stub’对象(具有正确id和关系但没有设置详细属性的对象),因此可以在以后需要时填写它们。
您当前的映射和/A/1.json
JSON适用于创建A
的存根实例和连接的B
的存根。
B/2.json
只会创建一个存根B
(它不会对A
做任何事情,因为映射没有附加关系信息)。 这是“故障”的映射,而不是JSON。 将RKRelationshipMapping
添加到B
的映射中,将创建存根并建立连接。
也就是说,你通常不会要求B
要求’反stub’,因为你通常需要请求A
才能得到B
最后,对于存根和细节,您不需要不同的映射。 只有1个映射,其中包含所有细节和id映射,RestKit将根据收到的JSON执行所有操作(因此,如果JSON只包含id,您将获得存根对象)。
为了建立Wain所说的,解决方案是:
- 建立双向RKRelationshipMappings
- 在为A和B对象发送JSON时,使用具有嵌套映射的映射。 防爆。 {“b”:{“b_id”:2,“a”:{“a_id”:1}}}
此外,如果您正在使用iOS模拟器,请确保将HTTP响应标头设置为不缓存内容。 由于我的代码使用了过时的数据,因此我多次坚持了这一点。