objective-c - NSPredicate 'OR' 基于 NSArray 键的过滤

标签 objective-c nsarray nspredicate foundation

考虑以下 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];

我能够过滤此数组以查找包含 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 中任何 键的字典对象的数据集。

例如,使用数组:NSArray *keySet = [NSArray arrayWithObjects:@"key1", @"key3", nil]; 我想创建一个返回数组的谓词和< em>任何 包含“key1”“key3”的字典对象(即在此示例中,将返回除第三个对象之外的所有字典对象 - 因为它不包含任何一个“key1”“key3”)。

关于如何实现这一点有什么想法吗?我必须使用复合谓词吗?

最佳答案

NSPredicateANY 运算符包括:

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

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

关于objective-c - NSPredicate 'OR' 基于 NSArray 键的过滤,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11115377/

相关文章:

ios - 新屏幕上的 UITextField 将不接受输入

iphone - NSData dataWithContentsOfURL : stopped working in iOS 6

objective-c - 如何读取和解析 .xml 文件

ios - 将 NSArray 的内容保存为纯文本文件而不是 xml

ios - onFormat string For NSPredicate

objective-c - 如何在 Objective-C++ 中返回 C++ 指针

ios - 在数组中查找重复的数字,然后计算重复的数量

ios - 在表格 View 单元格中检索数组的值swift ios

swift - 如何在核心数据中执行复杂的获取请求

swift - NSPredicate 获取第一个数字