Ready to Level-Up?

This just in! If your rusty iOS skills could use some refining, or if you're just starting out and you want to level-up fast, consider signing up for our upcoming iOS Screencasts

New from iOS Rocket Surgery Swift Video Tutorials: The rapidly evolving Apple-iOS ecosystem has just been thrown into tumult with the recent introduction of the Swift Programming Language. Are you ready to finally try iOS development? Are you needing to switch from Objective-C to Swift? Sign up today for our free video courses!
(By the dear folks at Swift Tutorial Videos, a sister company)

Tuesday, December 17, 2013

iOS NSFetchRequest with Predicates

So, you want to make an NSFetchRequest with NSPredicate filters, huh?

In a previous example, we showed you how to create and NSFetchRequest to fetch all of one kind of Entity. In this example, we'll show you how to filer your NSFetchRequest and pull in only entities that match certain criteria. Lets look at this example:


+(NSArray *)getEveryoneWithLastName:(NSString *)lastName andAge:(int)age inManagedObjectContext:(NSManagedObjectContext *)context
{
    // Create an NSFetchRequest for the People Entity
    NSFetchRequest *request = [NSFetchRequest fetchRequestWithEntityName:@"Person"];

    // Two predicate filters: last_name and age
    NSPredicate *lastNamePredicate = [NSPredicate predicateWithFormat:@"last_name = %@", lastName];
    NSPredicate *agePredicate = [NSPredicate predicateWithFormat:@"age = %d", age];

    // Build a compound predicate
    NSPredicate *compoundPredicate = [NSCompoundPredicate andPredicateWithSubpredicates:@[lastNamePredicate, agePredicate]];
  
    [request setPredicate:compoundPredicate];
  
    // No sorting this time    
    request.sortDescriptors = [NSArray arrayWithObjects:nil];
    
    NSError *error = nil;
    NSArray *people = [context executeFetchRequest:request error:&error];
    
    return people;
}


Here you see we are using two filters and have put the whole fetch inside of a static method. I like to include entity-specific fetcher code inside of model categories, because its a nice way to compartmentalize model code.

If this example was helpful to you, please give us a +1, thank you!





About Me

Easy NSDateFormatter Tool

Save yourself some time in formatting your NSDates to NSStrings, and use the Blind NSDate app, which you can download from iTunes. There's also a website where you can format your NSDates: http://www.blindnsdate.com

Popular Posts

Designed By Seo Blogger Templates