【问题标题】:Using NSPredicate to filter an NSMutableArray of NSDictionaries to find if a "key" exists使用 NSPredicate 过滤 NSDictionaries 的 NSMutableArray 以查找“键”是否存在
【发布时间】:2017-02-20 09:38:47
【问题描述】:

我有一个 NSMutableArray 的字典。我正在使用 NSPredicate 过滤数组以查找具有特定键的字典是否存在。

我提到了各种例子,最接近的例子之一在这里:Using NSPredicate to filter an NSArray based on NSDictionary keys。但是,我不希望密钥具有价值。我的问题是我想先找到钥匙。我尝试了不同的语法,但没有帮助。

到目前为止我做了什么:

    NSString *key = @"open_house_updated_endhour";
    NSPredicate *predicateString = [NSPredicate predicateWithFormat:@"%K", key];
    //NSPredicate *predicateString = [NSPredicate predicateWithFormat:@"%K contains [cd]", key]; Doesn't work.
    //NSPredicate *predicateString = [NSPredicate predicateWithFormat:@"%K == %@", key]; Won't work because it expects a value here.
    NSLog(@"predicate %@",predicateString);
    NSArray *filtered = [updatedDateAndTime filteredArrayUsingPredicate:predicate]; // updatedDateAndTime is the NSMutableArray

【问题讨论】:

  • 所以您只想知道数组中包含的字典中是否存在“某个键”?
  • @AdeelMiraj 是的,完全正确!这就是我想要的。
  • 在我看来,枚举数组将是相对更容易和直接的方式来做到这一点。通过谓词这样做有什么特别的原因吗?
  • @AdeelMiraj... 我这样做的原因是因为我对表格视图中的各种单元格有冗余逻辑。因此,我不想增加不必要的代码逻辑。另外,由于我是 iOS 新手,我想使用可用的 NSPredicate 系统来实现这个目标。

标签: objective-c nsdictionary nspredicate


【解决方案1】:

字典提供nil 作为缺失键的值。因此,只需将密钥与 nil 进行比较即可。

NSPredicate *predicateString = [NSPredicate predicateWithFormat:@"%K==NULL", key]; // Dictionaries not having the key
NSPredicate *predicateString = [NSPredicate predicateWithFormat:@"%K!=NULL", key]; // Dictionaries having the key

【讨论】:

  • 非常感谢您的快速帮助。它有帮助。我得到一个包含所需字典对象的数组(如果存在)。如果我想使用@"%K == NULL" || @"%K != NULL" ?如果我这样做,我会得到一个错误。基本上,如果找到密钥,我想更新字典。没关系,是否为空。毫无疑问,我喜欢这个简单的解决方案。
  • 我不明白,你为什么要使用@"%K == NULL" || @"%K != NULL"。首先在第一个NULL之后多了一个",这是什么错误。你能告诉我你得到的错误吗?但是,表达式总是正确的。这没有任何意义。
【解决方案2】:

试试看:

 NSArray *Myarray = [NSArray arrayWithObject:[NSMutableDictionary dictionaryWithObject:@"my hello string" forKey:@"name"]];   
NSArray *filteredarray = [Myarray filteredArrayUsingPredicate:[NSPredicate predicateWithFormat:@"(name == %@)", @"my hello string"]];
NSLog("%@",filteredarray);

另一个例子:

NSString *mycategory = @"iamsomeone";
NSArray *myitems = @[@{ @"types" : @[@"novel", @"iamsomeone", @"dog"] },
                   @{ @"types" : @[@"cow", @"iamsomeone-iam", @"dog"] },
                   @{ @"types" : @[@"cow", @"bow", @"cat"] }];
NSPredicate *mypredicate = [NSPredicate predicateWithBlock:^BOOL(id evaluatedObject, NSDictionary *bindings) {
    NSArray *categories = [evaluatedObject objectForKey:@"types"];
    return [categories containsObject:mycategory];
}];

NSArray *outpuArray = [myitems filteredArrayUsingPredicate:mypredicate];
NSLog(@"hello output:%@",outpuArray);

【讨论】:

  • 感谢您的快速回复。但是,第一个示例希望我对键有一个值。就我而言,它可能存在也可能不存在。因此,我想先检查密钥。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-11-11
  • 1970-01-01
  • 2012-01-16
  • 1970-01-01
相关资源
最近更新 更多