title: Handling duplicate entries in Core Data
body: <p>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. </p>
  
  <pre><code>-(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:&amp;err]){
                  NSLog(@"ERROR: Could not save context--%@", err);
              }
              return YES;            
          }
      return NO;
  }
  </code></pre>
  
  <p>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!</p>