使用NSPredicate基于多个键进行过滤(NOT值为key) [英] Using NSPredicate to filter based on multiple keys (NOT values for key)

查看:117
本文介绍了使用NSPredicate基于多个键进行过滤(NOT值为key)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下NSArray包含NSDictionary:

I have the following NSArray containing NSDictionary(s):

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匹配多个'keys' NSPredicate。

I am wanting to create a filtered NSArray that only contains objects where the NSDictionary matches multiple 'keys' using NSPredicate.

例如:


  • 过滤数组以仅包含NSDictionary对象具有键bill和joe[所需结果:新NSArray将包含两个NSDictionary对象]

  • 过滤数组以仅包含NSDictionary对象具有键joe和jenny[希望的结果:new NSArray将包含两个NSDictionary对象]

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

Can anyone please explain the format of the NSPredicate to achieve this?

编辑:
我可以使用以下方法实现类似的结果: / p>

I can achieve a similar outcome to desired NSPredicate using:

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会更加优雅,如果存在?

I'm imagining NSPredicate would be more elegant if one exists?

推荐答案

他们只有我知道是结合两个条件像'value1'IN列表AND'value2'IN列表

they only way I know is to combine two conditions like "'value1' IN list AND 'value2' IN list"

self。@ allKeys应该返回字典的所有键(self是数组中的每个字典)。如果你不用前缀@写它,那么字典只会寻找一个allKeys而不是 - (NSArray *)allKeys的方法。

self.@allKeys should return all the keys of the dictionary (self is each dictionary in your array). If you don't write it with the prefix @ then the dictionary will just look for a key that is "allKeys" instead of the method "- (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" ]]

这篇关于使用NSPredicate基于多个键进行过滤(NOT值为key)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆