Lion789
Lion789

Reputation: 4482

How to avoid duplicates when adding to core data?

I am trying to figure out how to avoid duplicate data being added? I would like to do it by having columns with unique rows, and if the column is not unique then to disallow the whole row to be added. Currently I add the row like this...

if([userProfileId isEqualToString: myId]) {
                     User *users = [NSEntityDescription insertNewObjectForEntityForName:@"User" inManagedObjectContext: _managedObjectContext];
                     int i = 0;

                     for(i = 0; i < responseCount; i++) {
                         [users setUserId:userIds[i]];
                         [users setName:names[i]];
                         [users setDateRetrieved:[NSDate date]];

                     }

                     //TODO HAVE TO AVOID DUPLICATE FROM BEING SAVED IN DB
                     NSError *error = nil;
                     if(![_managedObjectContext save:&error]) {
                         //handle error if it does not save
                     }
                     [self getDbData];

Upvotes: 0

Views: 98

Answers (1)

Bernhard Grabowski
Bernhard Grabowski

Reputation: 469

You can set an NSPredicate that reflects your unique content and run a fast query to see wether that content already exists:

Set the result type to NSManagedObjectIDResultType to speed things up:

fetchRequest.resultType = NSManagedObjectIDResultType;

and then get the count:

NSUInteger count = [self.managedObjectContext countForFetchRequest:fetchRequest error:&error];

And then check:

if (count > 0){

// The unique content already exists - do nothing 

}

if (count == 0){

// Save the unique content
}

Hope this helps.

Upvotes: 1

Related Questions