Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Handling duplicate entries in Core Data

I have an app that allows users to save favorites. I am using Core Data to store the favorites as managed objects. I have written some code to prevent the possibility of storing duplicates, but am wondering if there is a better way to do so. Each favorite object has an ID field that is unique. In the following code I am simply looping through and checking the ID field, and if the value already exists, setting a flag value to true, and breaking out of the loop.

-(BOOL)addFavorite{
    BOOL entityExists = NO;
    if(context){
        // does this favorite already exist?
        NSArray *allFaves = [AppDataAccess getAllFavorites];
        for(Favorite *f in allFaves){
            if([f.stationIdentifier isEqualToString:stID]){
                entityExists = YES;
                break;
            }
        }
        if(!entityExists){
            NSError *err = nil;
            Favorite *fave = [Favorite insertInManagedObjectContext:context];
            fave.stationRealName = riverGauge.name;
            fave.stationIdentifier = stID;
            fave.stationState = @"WV";
            if(![context save:&err]){
                NSLog(@"ERROR: Could not save context--%@", err);
            }
            return YES;            
        }
    return NO;
}

I was wondering if Core Data has the ability to check to see if an object being added is a duplicate. Is there a predicate that can handle checking for duplicates? Thanks!

like image 533
Pheepster Avatar asked Aug 15 '13 21:08

Pheepster


People also ask

Is it OK to have duplicate records in a data set?

Data aggregation and human typing errors are some of the sources of duplicate data. Customers may also provide a company with different information at different points in time. Hence, businesses should consider removing duplicate records from their Database.


2 Answers

Swift 4 Curled from @Vahid answer

func isEntityAttributeExist(id: Int, entityName: String) -> Bool {
    let appDelegate = UIApplication.shared.delegate as! AppDelegate
    let managedContext = appDelegate.persistentContainer.viewContext
    let fetchRequest = NSFetchRequest<NSFetchRequestResult>(entityName: entityName)
    fetchRequest.predicate = NSPredicate(format: "id == %@", id)
    let res = try! managedContext.fetch(fetchRequest)
    return res.count > 0 ? true : false
}
like image 142
Tosin Onikute Avatar answered Sep 24 '22 18:09

Tosin Onikute


Just an update since iOS 9.0 you can do it easily with "unique constraints" in the model. But pay attention - if your store already contains duplicates , core data will fail any auto migration when the app shipped.

See here for example - core data unique constraints

like image 26
shannoga Avatar answered Sep 24 '22 18:09

shannoga