0

我有一个NSArraywith NSDictionaries。每个字典都有一个 BOOL 值的键。

我需要对该数组进行排序,结果应该是 2 NSArrays:一个带有 0 值的字典,另一个带有 1 值的字典。

这样做的最佳方法是什么?

4

2 回答 2

2

不确定这是否是您的意思,但是:

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];
    }
}

其中array是初始数组,每个 dict 中的 BOOL 值存储在@"key". 它还使用新的字典访问语法

于 2013-02-18T10:16:34.233 回答
1

我认为“最好”的方式是使用NSPredicates,例如:

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];
于 2013-02-18T10:23:02.177 回答