-1
我有NSMutableArray其中包含人員列表,現在我需要獲取所有人的列表中的性別=男性,我該怎麼做?我應該進入NSPredicates嗎?NSArray,如何獲取基於屬性值的項目
我有NSMutableArray其中包含人員列表,現在我需要獲取所有人的列表中的性別=男性,我該怎麼做?我應該進入NSPredicates嗎?NSArray,如何獲取基於屬性值的項目
複製到某個地方在代碼
@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
然後,你需要得到男性的:
NSArray* males = [people arrayWithPredicate:^BOOL(id obj) {
// Gender check
}];
與NSPredicate
相比,您不必使用字面條g來指定標準(如果標準很複雜,則相當麻煩)。
是的,你可以使用這樣,這NSArray
類別
NSArray *filtered = [data filteredArrayUsingPredicate:[NSPredicate predicateWithFormat:@"self.gender == %@", @"male"]];
NSLog(@"%@",filtered);