【问题标题】:Using NSPredicate to filter based on multiple keys (NOT values for key)使用 NSPredicate 过滤基于多个键(不是键的值)
【发布时间】:2012-06-14 09:19:20
【问题描述】:

我有以下包含 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 存在的话会更优雅?

【问题讨论】:

    标签: objective-c cocoa nsarray nspredicate


    【解决方案1】:

    我知道的唯一方法是结合两个条件,例如“'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" ]]
    

    【讨论】:

    • 他也可以使用 NSCompoundPredicate 的 +andPredicateWithSubpredicates: 而不是硬编码只有 2 个选项。
    • 谢谢。我早上试试这个。代码看起来像我想要的!
    • 好吧..终于回到了这个。代码有效,只需要确保它是 alloc init-ed:NSArray* billAndJoe = [[NSArray alloc] initWithArray: [NSArray arrayWithArray:[data filteredArrayUsingPredicate:[NSPredicate predicateWithFormat:@"%@ IN self.@allKeys AND %@ IN self.@allKeys" , @"bill",@"joe" ]]]];
    • 实际上废弃了 - 它的工作原理与 Alexander 上面写的完全一样。 [得到下一杯咖啡..]。
    【解决方案2】:

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

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

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

    【讨论】:

      猜你喜欢
      • 2012-06-22
      • 1970-01-01
      • 1970-01-01
      • 2011-03-27
      • 1970-01-01
      • 2010-10-31
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多