RestKit - Hydrate数组外键

时间:2012-12-05 15:08:41

标签: objective-c ios cocoa-touch core-data restkit

我有以下JSON:

{
    "users": [
        {"id": "1", "name": "John Doe"},
        {"id": "2", "name": "Bill Nye"}
    ],
    "groups": [
        {"id": "1", "name": "Group1", "users": ["1", "2"]},
        {"id": "2", "name": "Group2", "users": ["1"]}
    ]
}

...以及包含User和Group对象的Core Data模型。组对象与用户具有多对多关系(NSSet)。

我发现以下线程似乎表明这是可能的,但没有解释如何执行这样的映射:

https://github.com/RestKit/RestKit/issues/284

如何执行此映射,以便每个组的“用户”关系正确连接?

注意:我设置了映射,可以将JSON用户和组正确映射到各自的Core Data对象。但是,每个组的“用户”NSSet都是空的。

2 个答案:

答案 0 :(得分:3)

所以,我用RestKit 0.20(pre2)来计算它。

需要将JSON更改为以下内容(请注意组的users数组中的属性名称):

{
    "users": [
        {"id": "1", "name": "John Doe"},
        {"id": "2", "name": "Bill Nye"}
    ],
    "groups": [
        {"id": "1", "name": "Group1", "users": [{"id" : "1"}, {"id" : "2"}]},
        {"id": "2", "name": "Group2", "users": [{"id" : "1"}]}
    ]
}

然后,以下映射:

RKEntityMapping *userMapping = [RKEntityMapping mappingForEntityForName:@"User" inManagedObjectStore:managedObjectStore];
userMapping.identificationAttributes = @[@"id"];
[userMapping addAttributeMappingsFromArray:@[@"id", @"name"]];
RKEntityMapping *groupMapping = [RKEntityMapping mappingForEntityForName:@"Group" inManagedObjectStore:managedObjectStore];
groupMapping.identificationAttributes = @[@"id"];
[groupMapping addAttributeMappingsFromArray:@[@"id", @"name"]];
[groupMapping addRelationshipMappingWithSourceKeyPath:@"users" mapping:userMapping];

最后,以下responseDescriptors:

RKResponseDescriptor *userResponseDescriptor = [RKResponseDescriptor responseDescriptorWithMapping:classMapping pathPattern:@"/api/allthejson" keyPath:@"users" statusCodes:RKStatusCodeIndexSetForClass(RKStatusCodeClassSuccessful)];
RKResponseDescriptor *groupResponseDescriptor = [RKResponseDescriptor responseDescriptorWithMapping:classMapping pathPattern:@"/api/allthejson" keyPath:@"groups" statusCodes:RKStatusCodeIndexSetForClass(RKStatusCodeClassSuccessful)];
[objectManager addResponseDescriptorsArray:@[userResponseDescriptor, groupResponseDescriptor]];

然后使用RKObjectManager的getObjectsAtPath获取对象:参数:success:failure方法和你的完成!

答案 1 :(得分:1)

RestKit存在许多问题,特别是在建模关系方面。调试映射可能令人生畏。

以下是一些代码,用于处理您在没有RestKit的情况下所描述的内容。

NSArray *userArray; 
// an array populated with NSManagedObjects 
// correctly converted from JSON to the User entity

NSArray *groups = [jsonObject objectForKey:@"groups"];

for (NSDictionary *d in groups) {
   Group *g = [NSEntityDescription insertNewObjectForEntityForName:@"Group"
                  inManagedObjectContext:_managedObjectContext];
   g.id = @([d[@"id"] intValue]);
   g.name = d[@"name"];
   NSArray *users = d[@"users"];
   for (NSString *s in users) {
      User *u = [[userArray filteredArrayUsingPredicate:
        [NSPredicate predicateWithFormat:@"id = %@", @([s intValue])]]
          objectAtIndex:0];
      [g addUsersObject:u];
   }
}
// save