November 17, 2010

Using Predicate to filter NSMutableArray

To filter NSMutableArray you could use Predicates in Objective-C. This will returns a new array which matches to the given predicate.


NSMutableArray *list =
    [NSMutableArray arrayWithObjects:@"Mark", @"Balmer", @"Bill", @"Steve", nil];
NSPredicate *listBPredicate = [NSPredicate predicateWithFormat:@"SELF beginswith[c] 'b'"];
NSArray *namesBeginB = [list filteredArrayUsingPredicate:listBPredicate];

NSPredicate *listContainsPredicate = [NSPredicate predicateWithFormat:@"SELF contains[c] 'e'"];

NSArray *namesWithE = [list filterArrayUsingPredicate:listContainsPredicate];

listBPredicate will return names which starts in "b" and listContainsPredicate will return all the names which has letter "e".

No comments: