10

我有以下包含 NSDictionary(s) 的 NSArray:

NSArray *data = [[NSArray alloc] initWithObjects:
                 [NSDictionary dictionaryWithObjectsAndKeys:[NSNumber numberWithInt:1], @"bill", [NSNumber numberWithInt:2], @"joe", nil],
                 [NSDictionary dictionaryWithObjectsAndKeys:[NSNumber numberWithInt:3], @"bill", [NSNumber numberWithInt:4], @"joe", [NSNumber numberWithInt:5], @"jenny", nil],
                 [NSDictionary dictionaryWithObjectsAndKeys:[NSNumber numberWithInt:6], @"joe", [NSNumber numberWithInt:1], @"jenny", nil],
                 nil];

我想创建一个过滤的 NSArray,它只包含 NSDictionary 使用 NSPredicate 匹配多个“键”的对象。

例如:

  • 过滤数组以仅包含具有键“bill”和“joe”的 NSDictionary 对象[期望的结果:新的 NSArray 将包含两个 NSDictionary 对象]
  • 过滤数组以仅包含键为“joe”和“jenny”的 NSDictionary 对象[期望结果:新的 NSArray 将包含最后两个 NSDictionary 对象]

任何人都可以解释 NSPredicate 的格式来实现这一点吗?

编辑:我可以使用以下方法实现与所需 NSPredicate 类似的结果:

NSMutableArray *filteredSet = [[NSMutableArray alloc] initWithCapacity:[data count]];
NSString *keySearch1 = [NSString stringWithString:@"bill"];
NSString *keySearch2 = [NSString stringWithString:@"joe"];

for (NSDictionary *currentDict in data){
    // objectForKey will return nil if a key doesn't exists.
    if ([currentDict objectForKey:keySearch1] && [currentDict objectForKey:keySearch2]){
        [filteredSet addObject:currentDict];
    }
}

NSLog(@"filteredSet: %@", filteredSet);

我想象 NSPredicate 如果存在会更优雅?

4

2 回答 2

24

我知道的唯一方法是结合两个条件,例如“'value1' IN list AND 'value2' IN list”

self.@allKeys 应该返回字典的所有键(self 是数组中的每个字典)。如果您不使用前缀 @ 编写它,那么字典将只查找“allKeys”而不是方法“- (NSArray*) allKeys”的键

编码:

NSArray* billAndJoe = [data filteredArrayUsingPredicate:[NSPredicate predicateWithFormat:@"%@ IN self.@allKeys AND %@ IN self.@allKeys" , @"bill",@"joe" ]];


NSArray* joeAndJenny = [data filteredArrayUsingPredicate:[NSPredicate predicateWithFormat:@"%@ IN self.@allKeys AND %@ IN self.@allKeys" , @"joe",@"jenny" ]]
于 2012-06-11T13:59:40.090 回答
5

由于如果您要求一个不存在的键的值,字典只会返回nil,因此指定该值应该是非零就足够了。如下格式应涵盖您的第一种情况:

[NSPredicate predicateWithFormat: @"%K != nil AND %K != nil", @"bill", @"joe"]

第二种情况,“joe”和“jenny”当然遵循类似的模式。

于 2012-06-11T13:59:39.917 回答