Mapping relationships in RestKit through an array of IDs doesn't work

后端 未结 1 742
青春惊慌失措
青春惊慌失措 2020-12-17 04:22

I\'m trying to map users and groups to CoreData objects through RestKit, maintaining the relationship between the two.

The JSON for the users is something like

1条回答
  •  时光说笑
    2020-12-17 05:00

    Found a way to make this work, and also realized that the updated approach in my question is only supposed to be used for nested objects, not referenced objects. This thread got me on the right track: https://groups.google.com/forum/#!msg/restkit/swB1Akv2lTE/mnP2OMSqElwJ (worth reading if you're dealing with relationships in RestKit)

    Assume the groups JSON still looks like the original JSON:

    {"groups":
      [{"name": "John's group", "_id": "a",
        "members": ["1", "2"]
       ...
      ]
    }
    

    Also assume that users are mapped to a keypath users (i.e. as in something like [objectManager.mappingProvider setMapping:userMapping forKeyPath:@"users"];) the correct way to map the relationships looks like this:

    RKObjectManager* objectManager = [RKObjectManager sharedManager];
    RKManagedObjectMapping* groupMapping = [RKManagedObjectMapping mappingForClass:[Group class] inManagedObjectStore:objectManager.objectStore];
    groupMapping.primaryKeyAttribute = @"identifier";
    [groupMapping mapKeyPath:@"_id" toAttribute:@"identifier"];
    [groupMapping mapKeyPath:@"name" toAttribute:@"name"];
    [groupMapping mapKeyPath:@"members" toAttribute:@"memberIDs"];
    [objectManager.mappingProvider setMapping:groupMapping forKeyPath:@"groups"];
    
    [groupMapping mapKeyPath:@"users" toRelationship:@"members" withMapping:[[RKObjectManager sharedManager].mappingProvider objectMappingForKeyPath:@"users"] serialize:NO];
    [groupMapping connectRelationship:@"members" withObjectForPrimaryKeyAttribute:@"memberIDs"];
    
    RKObjectRouter* router = objectManager.router;
    [router routeClass:[Group class] toResourcePath:@"/rest/groups/:identifier"];
    [router routeClass:[Group class] toResourcePath:@"/rest/groups/" forMethod:RKRequestMethodPOST];
    // Assume url is properly defined to point to the right path...
    [[RKObjectManager sharedManager] loadObjectsAtResourcePath:url usingBlock:^(RKObjectLoader *loader) {}];
    

    When I had tried this approach earlier, the thing that confused me was this line

    [groupMapping mapKeyPath:@"users" toRelationship:@"members" withMapping:[[RKObjectManager sharedManager].mappingProvider objectMappingForKeyPath:@"users"] serialize:NO];
    

    where the first key path is referring to the key path mapping for the objects being referenced (users in this case), not the key path of the relationship within the group object being mapped (which would have been members in this case).

    With this change, all relationships work as expected and I'm happy.

    0 讨论(0)
提交回复
热议问题