7

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.

Verbeia
  • 4,400
  • 2
  • 23
  • 44

2 Answers2

1

No, that is not the case, as Core Data keeps its own keys. You can easily solve this problem by checking if your primary key exists and before saving the entity instance in question.

Mundi
  • 79,884
  • 17
  • 117
  • 140
  • That's means each time I want to save the context, I must loop on each entities of the managed context to check if the entity exist in sqlite db ? Restkit does not provide something ? Or core data ? –  Nov 19 '11 at 11:20
  • 1
    Basically, yes. Or, before you create a new item, fetch it from the database. If the fetch comes back empty, create it, otherwise don't even insert it into the managed object context. I did it this way and it is quite efficient. – Mundi Nov 19 '11 at 11:23
  • 1
    I've the same problem with duplications, however Restkit do provide a check before insert into database, but it seems not to be calling with me (and you) for some reason. Check out how I "solved" temporarily, until I find the right answer http://stackoverflow.com/questions/7799890/primarykeyattribute-not-working-restkit-core-data – mateusmaso Nov 19 '11 at 16:25
  • Exactly... see my answer! – electronix384128 Jul 28 '14 at 22:00
0

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.

electronix384128
  • 6,625
  • 11
  • 45
  • 67