0
votes

I have a Json file, that is structured roughly like this:

{
    "id": "1",
    "child1": {
        "p1": "v1",
        "p2": "v2"
    },
    "child2": {
        "p1": "v1",
        "p2": "v2"
    }
}

The child1 and child2 properties are mapped through a relationship mapping and both use the same RKEntityMapping. In order for restkit to be able to properly do the uniqueness, I wanted to have an extra field type that would then have the value child1 or child2 depending on which item it is. I wanted to use @metadata.mapping.rootKeyPath, but that always has nil.

My relationship mapping:

RKEntityMapping *childMapping = [RKEntityMapping mappingForEntityForName:@"Child" inManagedObjectStore:managedObjectStore];
[childMapping addAttributeMappingsFromDictionary:@{@"@parent.id" : @"userID", @"@metadata.mapping.rootKeyPath" : @"type"}];
[childMapping addAttributeMappingsFromArray:@[@"p1", @"p2"]];
childMapping.identificationAttributes = @[@"userID", @"type"];
[entityMapping addPropertyMapping:[RKRelationshipMapping relationshipMappingFromKeyPath:@"child1"
                                                                              toKeyPath:@"child1"
                                                                                withMapping: childMapping]];
[entityMapping addPropertyMapping:[RKRelationshipMapping relationshipMappingFromKeyPath:@"child2"
                                                                                   toKeyPath:@"child2"
                                                                                 withMapping: childMapping]];

Is there a way to get the rootKeyPath in a relationship mapping, so that I can use it as an identificationAttribute? Or maybe another workaround to achieve that?

1
is there a reason the child objects don't have a unique id from the server ? - Wain
They are never independent from the main object. So a unique key from them isn't really necessary. - viirus

1 Answers

0
votes

I think in this case I'd add some logic into the model class so that before it's saved it interrogates its relationships and values to generate a unique identifier. Based on your sample data the 2 children would still be the same object except for the relationship they're being mapped into, so you can use the name of the non-nil relationship to determine what they are.

This doesn't help with RestKit uniquing because the identifier isn't in the JSON.

So, here, you'd want a fetch request block to clean up any orphaned children (who have no relationship to any parent).