Compound Predicates – “get me objects with these specific ID’s!”

So, I’m hoping you know about Predicates and how they make finding or filtering objects really easy. If not, head over to NSHipster and read up on that.

I had a particular use case, where I had an array of objectID’s (NSNumber objects) that I needed to fetch from my CoreData context.

So the question of “how do I get an array of objects with specific, known, object id’s?” The Answer? Compound Predicates.

The Recipe:

// I use MagicalRecord for CoreData.  Get your object context how you normally would then...
NSManagedObjectContext *context = [NSManagedObjectContext MR_contextForCurrentThread];  
NSMutableArray *predicates = [NSMutableArray array];
for (NSNumber *knownId in knownObjectIds) {
  // assuming your object has the property myObjectId
  NSPredicate *predicate = [NSPredicate predicateWithFormat:@"myObjectId == %@", knownId]; 
  [predicates addObject: predicate];  
NSPredicate *compoundPredicate = [NSCompoundPredicate orPredicateWithSubpredicates:predicates];
// like I say, I'm thrilled with MagicalRecord.  
//  This is where you would use this for your fetch request in CoreData
NSArray *fetchedResults = [HSCoreDataObject MR_findAllWithPredicate:compoundPredicate inContext:context];