Handling duplicate entries in Core Data

CoreData does no uniquing by itself. It has no notion of two entries being identical.

To enable such a behavior you have to implement it yourself by doing a 'search before insert' aka a 'fetch before create'.

NSFetchRequest *fetch = [NSFetchRequest fetchRequestWithEntityName:@"Favorite"];
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"stationIdentifier == %@", stID];
[fetch setPredicate:predicate];
YourObject *obj = [ctx executeRequest:fetch];

if(!obj) {
    //not there so create it and save
    obj = [ctx insertNewManagedObjectForEntity:@"Favorite"]; //typed inline, dont know actual method
    obj.stationIdentifier = stID;
    [ctx save];
}

//use obj... e.g.
NSLog(@"%@", obj.stationIdentifier);

Remember this assumes single-threaded access


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


Swift 3:

func isExist(id: Int) -> Bool {
    let fetchRequest = NSFetchRequest<NSFetchRequestResult>(entityName: myEntityName)
    fetchRequest.predicate = NSPredicate(format: "id = %d", argumentArray: id)

    let res = try! theContext.fetch(fetchRequest)
    return res.count > 0 ? true : false
}