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]; 
Advertisements

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

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s