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!
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.
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
}
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With