NSPredicate 基于键的 NSArray 的“OR"过滤 [英] NSPredicate 'OR' filtering based on an NSArray of keys

查看:39
本文介绍了NSPredicate 基于键的 NSArray 的“OR"过滤的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

考虑以下 NSArray:

Consider the following NSArray:

NSArray *dataSet = [[NSArray alloc] initWithObjects:
                 [NSDictionary dictionaryWithObjectsAndKeys:@"abc", @"key1", @"def", @"key2", @"hij", @"key3", nil], 
                 [NSDictionary dictionaryWithObjectsAndKeys:@"klm", @"key1", @"nop", @"key2", nil], 
                 [NSDictionary dictionaryWithObjectsAndKeys:@"qrs", @"key2", @"tuv", @"key4", nil], 
                 [NSDictionary dictionaryWithObjectsAndKeys:@"wxy", @"key3", nil], 
                 nil];

我能够过滤此数组以查找包含 key key1

I am able to filter this array to find dictionary objects that contain the key key1

// Filter our dataSet to only contain dictionary objects with a key of 'key1'
NSString *key = @"key1";
NSPredicate *key1Predicate = [NSPredicate predicateWithFormat:@"%@ IN self.@allKeys", key];
NSArray *filteretSet1 = [dataSet filteredArrayUsingPredicate:key1Predicate];
NSLog(@"filteretSet1: %@",filteretSet1);

哪个适当地返回:

filteretSet1: (
        {
        key1 = abc;
        key2 = def;
        key3 = hij;
    },
        {
        key1 = klm;
        key2 = nop;
    }
)

现在,我想过滤包含 NSArray 中键的 ANY 的字典对象的数据集.

Now, I am wanting to filter the dataSet for dictionary objects containing ANY of the keys in an NSArray.

例如,使用数组: NSArray *keySet = [NSArray arrayWithObjects:@"key1", @"key3", nil]; 我想创建一个谓词,返回和数组 any 包含 'key1' 'key3' 的字典对象(即,在这个例子中,除了第三个对象之外的所有字典对象都将被返回——因为它不包含任何一个'key1' 'key3').

For example, using the array: NSArray *keySet = [NSArray arrayWithObjects:@"key1", @"key3", nil]; I want to create a predicate that returns and array of any dictionary objects that contain either 'key1' or 'key3' (ie. in this example all dictionary objects would be returned except for the third object - as it does not contain either 'key1' or 'key3').

关于我如何实现这一目标的任何想法?我是否必须使用复合谓词?

Any ideas on how I would achieve this? Would I have to use a compound predicate?

推荐答案

NSPredicateANY 操作符涵盖了这个:

The ANY operator of NSPredicate covers this:

NSSet *keys = [NSSet setWithObjects:@"key1", @"key3", nil];

NSPredicate *key1Predicate = [NSPredicate predicateWithFormat:@"any self.@allKeys in %@", keys];

这篇关于NSPredicate 基于键的 NSArray 的“OR"过滤的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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