Search code examples
iosjsoncocoacore-datarestkit

RestKit primary key attribute


I load data from a json file, I save it. I do it twice ... I got two entries in my Core Data sqlite database. Even if I set in the mapping the primaryKeyAttribute.

 mapping.primaryKeyAttribute = @"code";
    [mapping mapAttributesFromArray :mappedFields];
    [[RKObjectManager sharedManager].mappingProvider setMapping:mapping forKeyPath:entityName];  

My Json

{ "MyEntity": [ { "code" : "axv2","data" : "content"}]};

Here the callback :

- (void)objectLoader:(RKObjectLoader*)objectLoader didLoadObjects:(NSArray*)objects {

    NSLog(@"Entries loaded %d",[objects count]);
    lastResult = objects;

    for(MyEntity * myEntity in lastResult) {       
        [self saveContext];       
    }
}

My entity is correctly mapped ... But Restkit allow one to save duplicate entries with the same primary key?

It's weird, I understood that this primary key attribute would avoid this problem.


Solution

  • As of the latest RESTKit version (0.23.2) you can define the primary key like this:

    [_mapping addAttributeMappingsFromDictionary:@{ @"id" : @"objectId", @"name" : @"name" }];
    [_mapping setIdentificationAttributes:@[ @"objectId" ]];
    

    Whereas objectId is you primary key on the core data object.