NSPredicate

Episode #101 | 9 minutes | published on January 2, 2014
Subscribers Only
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]);
blog comments powered by Disqus