title: What is the most efficient way to sync Core Data with JSON API
body: <p>What would be the best way to sync my Core Data schema with a remote API serving JSON? At the moment I'm looping through each dictionary in the JSON response checking Core Data to see if the API ID exists. </p>
  
  <p>This works great, but all thats left to do now is delete any local objects that aren't on the server. Here is an example of my JSON data:</p>
  
  <pre><code>[
     {
        "id":1234,
        "name":"My first object",
        "description":"This is a long string with lots of information"
     },
     {
        "id":1235,
        "name":"My second object",
        "description":"This is a long string with lots of information"
     }
  ]
  </code></pre>
  
  <p>Currently the only way I can think of accomplishing this is something like the following:</p>
  
  <pre><code>NSArray *jsonData = // Convert json data to array using NSJSONSerialization
  NSInteger fetchedCount = _fetchedResultsController.fetchedObjects.count;
  
  if (fetchedCount != jsonData.count) {
  
      for (int i = 0; i &lt; fetchedCount; i++) {
  
          NSManagedObject *object = [_fetchedResultsController objectAtIndexPath: [NSIndexPath indexPathForItem:i
                                                                                                      inSection:0]];
          NSNumber *idNumber = object.apiID;
  
          BOOL shouldDelete = YES;
  
          for (NSDictionary *jsonDict in jsonData) {
              if ([jsonDict  objectForKey:@"id"] == idNumber) {
                  shouldDelete = NO;
              }
          }
  
          if (shouldDelete) {
  
              // Delete object.
          }            
      }
  }
  </code></pre>
  
  <p>I think that will be massively inefficient if the JSON array contains a lot of objects.</p>