使用 NSPredicate 过滤 NSDictionaries 的 NSMutableArray 以查找是否存在 "key"

Using NSPredicate to filter an NSMutableArray of NSDictionaries to find if a "key" exists

我有一个字典的 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

试一试:

 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);

字典提供 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