DaGaMs
DaGaMs

Reputation: 1557

How to achieve `hasOne:withMapping:` in RestKit 0.20?

I have a JSON data-structure for items of the sort

{
    "id": "8a1a39479d03d959", 
    "sortOrder": 3, 
    "timestamp": 1381669499.11, 
}

and another file structure that has exactly one item:

{
    "id": "d88e3c3d1630db4c", 
    "item": "8a1a39479d03d959", 
    "timestamp": 1381669505.364, 
    "version": 2
}

I've been struggling to get this sort of mapping to work, to the point that I added a list of [files] to the items JSON just to map the relationship. However, reading an older post on the Google group, I saw that it supposedly used to be possible to map these relationships like this (not tested code, just paraphrasing the above link):

RKManagedObjectMapping *itemMapping = [RKManagedObjectMapping mappingForClass:[Item class]];
itemMapping.primaryKeyAttribute = @"itemID";
[itemMapping mapKeyPath:@"sortOrder" toAttribute:@"sortOrder"];
[itemMapping mapKeyPath:@"id" toAttribute:@"itemID"];

RKManagedObjectMapping *fileMapping = [RKManagedObjectMapping mappingForClass:[File class]];
fileMapping.primaryKeyAttribute = @"fileID";
[fileMapping mapKeyPath:@"id" toAttribute:@"fileID"];
[fileMapping mapKeyPath:@"item" toAttribute:@"itemID"];
[fileMapping mapKeyPath:@"version" toAttribute:@"version"];

[fileMapping hasOne:@"item" withMapping:itemMapping];
[fileMapping connectRelationship:@"organization" withObjectForPrimaryKeyAttribute:@"itemID"];

However hasOne:withMapping: doesn't exist any more in RestKit 0.20. What is the correct way nowadays to map a one-to-many relationship with an id returned as a simple string in the JSON? Just for reference, I am using CoreData integration in this project.

Upvotes: 1

Views: 117

Answers (2)

Wain
Wain

Reputation: 119031

Ok, your mapping sets the item identity to identifier. On the file this corresponds to nothing - it needs to. Add a transient attribute and map the item to it (let's call it itemIdentifier). Now, you can setup a relationship mapping to fill in the Core Data relationship (which should be bi-directional, I'm assuming item <<-> files):

[fileMapping addConnectionForRelationship:@"item" connectedBy:@{ @"itemIdentifier": @"identifier" }];

Upvotes: 1

scollaco
scollaco

Reputation: 922

Try this:

RKEntityMapping *mapping = [RKEntityMapping mappingForEntityForName:@"Item"
                                               inManagedObjectStore:[YourManagedObjectStore];
[mapping addAttributeMappingsFromDictionary:@{
                                              @"sortOrder": @"sortOrder",
                                              @"id":@"itemID"
                                              }];

mapping.identificationAttributes = @[@"itemID"];

[mapping addRelationshipMappingWithSourceKeyPath:@"organization"
                                         mapping:fileMapping];

I hope it helps.

Upvotes: 0

Related Questions