Episode #101

NSPredicate

9 minutes
Published on January 2, 2014

This video is only available to subscribers. Get access to this video and 572 others.

In this episode we look at a powerful built-in Foundation class called NSPredicate. With predicates we can easily filter large collections of data based on values contained in the collection.

Episode Links

Examples

Finding people under 18

NSPredicate *minors = [NSPredicate predicateWithFormat:@"age < 18"];
NSLog(@"Minors: %@", [people filteredArrayUsingPredicate:minors]);

Only 'A' Names

NSPredicate *aNames = [NSPredicate predicateWithFormat:
    @"lastName BEGINSWITH[cd] %@ OR firstName BEGINSWITH[cd] %@", @"a", @"a"];
NSLog(@"A names: %@", [people filteredArrayUsingPredicate:aNames]);

Filtering by state using substitution variables

NSPredicate *statePredicate = [NSPredicate predicateWithFormat:@"address.state == $state"];
NSPredicate *oregonians = [statePredicate predicateWithSubstitutionVariables:@{ @"state": @"OR" }];
NSPredicate *texans = [statePredicate predicateWithSubstitutionVariables:@{ @"state": @"TX"}];
NSLog(@"Oregonians: %@", [people filteredArrayUsingPredicate:oregonians]);    

Combining predicates using NSCompoundPredicate

NSPredicate *texasMinors = [[NSCompoundPredicate alloc] initWithType:NSAndPredicateType
                                                       subpredicates:@[ texans, minors]];
NSLog(@"Texas minors: %@", [people filteredArrayUsingPredicate:texasMinors]);