Finding duplicate values in core data

core-data, core-data-migration, ios, ios7, iphone

Solution

You can fetch or you can count. Counting is much faster than fetching. Depends on what you are trying to do.

If you just want to insert new and skip duplicates then use `-[NSManagedObjectContext countForFetchRequest: error:]` to determine if the object exists.

You can pre-build the predicate and just replace the unique value on each loop so that even the cost of the predicate is low. This is fairly performant but not the best solution because it hits the disk on each loop.

Another option would be to change the fetch to have:

- Just the unique value

- A NSDictionary result

Then grab all of the unique values from your insertable array into an array of strings (for example) then do a single fetch with:

[fetchRequest setPredicate:[NSPredicate predicateWithFormat:@"myUnique in %@", uniqueIDArray]];

Then you have an array of uniques that ARE in the store already. From there as you loop over your objects you check against that array, if the unique in there you skip, otherwise you insert. That will yield the best performance for a straight insert or skip requirement.

Problem

i'm inserting new objects into the database by core data. Is there any way to check if there is any duplicate in the database before i insert the values in? ``` AccountDetails * newEntry = [NSEntityDescription insertNewObjectForEntityForName:@"AccountDetails" inManagedObjectContext:self.managedObjectContext]; newEntry.acc_date=date; newEntry.bank_id=bank_id1; NSError *error; if (![self.managedObjectContext save:&error]) { NSLog(@"Whoops, couldn't save: %@", [error localizedDescription]); } [self.view endEditing:YES]; ``` everytime i run the app , it reinsert the values again. i want to check if there is any new category in it if there isnt then i will add that new one in only. thanks in advance..

Original source