Reputation: 1182
I have an NSArray
with NSDictionaries
.
Each of the dictionaries have a key for a BOOL value.
I need to sort through that array and the outcome should be 2 NSArrays
: one with the dictionaries with the 0 value, and the other with the dictionaries with the 1 value.
What's the best way of doing this?
Upvotes: 0
Views: 245
Reputation: 5499
I think the "best" way is using NSPredicates
, for example:
NSPredicate *yesPredicate = [NSPredicate predicateWithFormat:@"%K == %@", @"key", [NSNumber numberWithBool:YES]];
NSArray *filteredYESResults = [allResultsArray filteredArrayUsingPredicate:yesPredicate];
NSPredicate *noPredicate = [NSPredicate predicateWithFormat:@"%K == %@", @"key", [NSNumber numberWithBool:NO]];
NSArray *filteredNOResults = [allResultsArray filteredArrayUsingPredicate:noPredicate];
Upvotes: 1
Reputation: 5683
Not sure if this is what you mean but:
NSMutableArray *yesDicts = [NSMutableArray array];
NSMutableArray *noDicts = [NSMutableArray array];
for (NSDictionary *dict in array) {
NSNumber *yesorno = dict[@"key"];
if ([yesorno boolValue] == YES) {
[yesDicts addObject:dict];
} else {
[noDicts addObject:dict];
}
}
where array
is the initial array, and the BOOL value in each dict is stored at @"key"
.
Also it uses the new dictionary access syntax
Upvotes: 2