How to add mapping between not embedded JSON objects and relationships using RestKit 0.2 and Core Data?

cocoa-touch, core-data, ios, json, restkit

Solution

You want to use foreign key mapping to allow RestKit to connect the objects.

You need to add an image mapping and it should have an attribute to hold the `appId`. Then, you need to add a connection relationship:

[imageMapping addConnectionForRelationship:@"application" connectedBy:@{ @"appId": @"appId" }];

Which tells RestKit to use the `appId` attribute on the image instances to connect to application instances with the corresponding `appId` and to save the result in the `application` relationship.

Problem

I'm developing my first iOS application that uses RestKit 0.2 and Core Data. Most of the time I have followed this great tutorial http://www.alexedge.co.uk/blog/2013/03/08/introduction-restkit-0-20/ however it doesn't fit my requirements since it describes embedded JSON objects and I need to create separate objects. Here is a simplified scenario of my app structure: JSON response: ``` "application": [ { "appId": "148", "appName": … . . . (more attributes) } ], "image": [ { "imgId": "308", "appId": "148", "iType": "screenshot", "iPath": .. . . . }, { "imgId": "307", "appId": "148", "iType": "logo", "iPath": … . . . } ] ``` I have created a data model that contains two entities and set the relationship between them in a way that one application may have more than one image and one image may only belong to one application: I have used mogenerator to create classes represented by entities. I can successfully map the entity to Application object using the following code: ``` NSDictionary *parentObjectMapping = @{ @"appId" : @"appId" }; // Map the Application object RKEntityMapping *applicationMapping = [RKEntityMapping mappingForEntityForName:NSStringFromClass([Application class]) inManagedObjectStore:managedObjectStore]; applicationMapping.identificationAttributes = @[ @"appId" ]; [applicationMapping addAttributeMappingsFromDictionary:@{ @"appName" : @"name", @"appCat" : @"category", @"appType" : @"type", @"compName" : @"companyName", @"compWeb" : @"companyWebsite", @"dLink" : @"downloadWebLink", @"packageName" : @"appStoreLink", @"osMinVer" : @"minRequirements", @"appCost" : @"cost", @"appDescription" : @"appDescription" }]; [applicationMapping addAttributeMappingsFromDictionary:parentObjectMapping]; // Register our mappings with the provider [manager addResponseDescriptorsFromArray:@[ [RKResponseDescriptor responseDescriptorWithMapping:applicationMapping pathPattern:nil keyPath:@"application" statusCodes:RKStatusCodeIndexSetForClass(RKStatusCodeClassSuccessful)] ]]; ``` Now I have a problem when mapping the JSON to the image object with the appropriate relationship between Image and Application. How can I add the mapping between the two Entities? Is my data model correct or I'm missing something?

Original source