title: Most efficient way to insert/update records with Core Data?
body: <p>I am developing an app that downloads data from a server regularly. If the data needs updated, I use something like to following to update the records or insert new records if they don't exist. </p>
  
  <pre><code>let fetchRequest = NSFetchRequest&lt;NSFetchRequestResult&gt;(entityName: "Trip")
      for csvTrip in csvTrips {
          var trip: NSManagedObject!
  
          let tripId = Int(csvTrip[0])!
          fetchRequest.predicate = NSPredicate(format: "id = %d", tripId)
  
          if (context.count(for: fetch) == 0) {
              trip = NSEntityDescription.insertNewObject(forEntityName: "Trip", into: context)
              trip.setValue(tripId, forKey: "id")
          } else {
              tripObject = (context.fetch(fetch) as! [NSManagedObject])[0]
          }
  
          // Set other properties
      }
  </code></pre>
  
  <p>Checking if the entity already exists in each loop makes it about 100 times slower than just inserting them without checking, which becomes a big problem with more than a few thousand entities. I've tried fetching all the entities first, but I still have to loop through each one and add the id to an array or something, which isn't much faster. I know core data isn't the same as MySQL, but it's hard for me to believe that there isn't a feature similar to INSERT ... ON DUPLICATE KEY UPDATE, which is extremely fast in MYSQL. Am I missing something? </p>