I have NSMutableArray which contains a list of people , now I need to get a list of all people where gender = male, how can I do that? should I get into NSPredicates to do that?
Asked
Active
Viewed 823 times
2 Answers
2
Copy this NSArray
category to to somewhere in your code
@implementation NSArray (My)
-(NSArray*)arrayWithPredicate:(BOOL(^)(id obj))predicate {
NSMutableArray* objs = [NSMutableArray array];
[self enumerateObjectsUsingBlock:^(id o, NSUInteger idx, BOOL *stop) {
if (predicate(o)) {
[objs addObject:o];
}
}];
return objs;
}
@end
Then where you need to get the male ones:
NSArray* males = [people arrayWithPredicate:^BOOL(id obj) {
// Gender check
}];
The advantage over NSPredicate
is that you don't have to use a literal string to specify the criteria (quite a mess if the criteria is complex).

Khanh Nguyen
- 11,112
- 10
- 52
- 65
0
yes you can use like this,
NSArray *filtered = [data filteredArrayUsingPredicate:[NSPredicate predicateWithFormat:@"self.gender == %@", @"male"]];
NSLog(@"%@",filtered);

Balu
- 8,470
- 2
- 24
- 41