Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>I see two ways of doing this. It seems to me that the latter (your proposed method) is the better solution.</p> <p>I changed id to primaryKey since I don't think it would be a good idea to use id as a variable or method name in Object-C since it's a keyword. I might work, I've never really tried. Also I assumed primaryKey to be an NSNumber, since that is how would be stored in Core Data.</p> <p>Method One would execute a fetch request on the context each time:</p> <pre><code>for (id data in someSetOfDataToImport) { NSFetchRequest * request = [[NSFetchRequest alloc] init]; [request setEntity:[NSEntityDescription entityForName:@"Story" inManagedObjectContext:context]]; [request setPredicate:[NSPredicate predicateWithFormat:@"primaryKey = %d", primaryKey]]; NSUInteger count = [context countForFetchRequest:request error:nil]; [request release]; if (count &gt; 0) continue; // Insert data in Managed Object Context } </code></pre> <p>Method Two does what you proposed, cache the keys in an array and check it instead of going to the source:</p> <pre><code>NSFetchRequest * request = [[NSFetchRequest alloc] init]; [request setEntity:[NSEntityDescription entityForName:@"Story" inManagedObjectContext:context]]; NSArray * allStories = [context countForFetchRequest:request error:nil]; [request release]; NSMutableArray * allPrimaryKeys = [[allStories valueForKeyPath:@"@distinctUnionOfObjects.primaryKey"] mutableCopy]; for (id data in someSetOfDataToImport) { if ([allPrimaryKeys containsObject:data.primaryKey]) continue; [allPrimaryKeys addObject:data.primaryKey]; // Insert data in Managed Object Context } [allPrimaryKeys release]; </code></pre>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload