Friday, May 31, 2013

NSArray filteredArrayUsingPredicate example in Objective C (iOS).


NSArray filteredArrayUsingPredicate

Evaluates a given predicate against each object in the receiving array and returns a new array containing the objects for which the predicate returns true.

- (NSArray *)filteredArrayUsingPredicate:(NSPredicate *)predicate

Parameters
predicate
The predicate against which to evaluate the receiving array’s elements.

Return Value
A new array containing the objects in the receiving array for which predicate returns true.

Discussion of [NSArray filteredArrayUsingPredicate]
For more details, see Predicate Programming Guide.

NSArray filteredArrayUsingPredicate example.
NSMutableArray *array =
    [NSMutableArray arrayWithObjects:@"Bill", @"Ben", @"Chris", @"Melissa", nil];

NSPredicate *bPredicate =
    [NSPredicate predicateWithFormat:@"SELF beginswith[c] 'b'"];
NSArray *beginWithB =
    [array filteredArrayUsingPredicate:bPredicate];
// beginWithB contains { @"Bill", @"Ben" }.

NSPredicate *sPredicate =
    [NSPredicate predicateWithFormat:@"SELF contains[c] 's'"];
[array filterUsingPredicate:sPredicate];
// array now contains { @"Chris", @"Melissa" }

Example of [NSArray filteredArrayUsingPredicate].
- (NSArray *)myFilteredObjects {
    NSPredicate *pred = [NSPredicate predicateWithFormat:@"myMethod = TRUE"];
    return [myArray filteredArrayUsingPredicate:pred];
}

NSArray filteredArrayUsingPredicate example.
NSArray *data = [NSArray arrayWithObject:[NSMutableDictionary dictionaryWithObject:@"foo" forKey:@"BAR"]];   
NSArray *filtered = [data filteredArrayUsingPredicate:[NSPredicate predicateWithFormat:@"(BAR == %@)", @"foo"]];

End of NSArray filteredArrayUsingPredicate example article.