我有一个字典的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
答案 0 :(得分:3)
字典提供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
答案 1 :(得分:0)
试一试:
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);