Saturday, June 1, 2013

NSMutableArray filterUsingPredicate example in Objective C (iOS).


NSMutableArray filterUsingPredicate

Evaluates a given predicate against the array’s content and leaves only objects that match

- (void)filterUsingPredicate:(NSPredicate *)predicate

Parameters of [NSMutableArray filterUsingPredicate]
predicate
The predicate to evaluate against the array's elements.

NSMutableArray filterUsingPredicate example.
NSArray *array = [[self.myArray copy] autorelease];
NSPredicate *predicate = [NSPredicate predicateWithBlock:^BOOL(id evaluatedObject, NSDictionary *bindings) {       
    if ([array indexOfObject:evaluatedObject] < 10) return YES;
    return evaluatedObject.distanceFromCurrent <= 25;
}];
[self.myArray filterUsingPredicate:predicate];

Example of [NSMutableArray filterUsingPredicate].
NSMutableArray *array=...;
[array filterUsingPredicate:[NSPredicate predicateWithBlock:^BOOL(id evaluatedObject, NSDictionary *bindings) {
    CustomObject *customObject=(CustomObject *) evaluatedObject;
    return (customObject.name!=nil);
}]];

NSMutableArray filterUsingPredicate example.
- (void)clientSearch:(NSTimer*)timer
{
[COLOR=\"Red\"]
    NSMutableArray *searchArray = [NSMutableArray arrayWithArray:[clientArray copy]];
[/COLOR]    //searchArray = [clientArray copy];
    NSString *name = timer.userInfo;
    NSLog(@\"Search String = %@\", name);
   
    NSPredicate* predicate = [NSPredicate predicateWithFormat:[NSString stringWithFormat:@\"ClientName contains[c] '%@'\", name]];
    [searchArray filterUsingPredicate:predicate];
    NSLog(@\"Filtered Array Contains: %@\", searchArray);
[COLOR=\"Red\"]    clientArray = [searchArray copy];
[/COLOR]   
    [self.searchDisplayController.searchResultsTableView reloadData];
   
}

End of NSMutableArray filterUsingPredicate example article.