NSPredicate'OR'过滤基于NSArray键

时间:2012-06-20 08:13:54

标签: 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中键的 ANY 的字典对象的dataSet。

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

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

3 个答案:

答案 0 :(得分:9)

ANY的{​​{1}}运算符涵盖了这一点:

NSPredicate

答案 1 :(得分:1)

这样做:

   NSString *key = @"key1";
   NSString *key1 = @"key3";
   NSPredicate *key1Predicate = [NSPredicate predicateWithFormat:@"%@ IN self.@allKeys OR %@ IN self.@allKeys",key,key1];
   NSArray *filteretSet1 = [dataSet filteredArrayUsingPredicate:key1Predicate];
   NSLog(@"filteretSet1: %@",filteretSet1);

完美适合我。希望有用

答案 2 :(得分:1)

尽管问题已得到解答,您还可以使用块来获得更多粒度:

NSArray *filter = [NSArray arrayWithObjects:@"key1", @"key3",nil];

NSPredicate *filterBlock = [NSPredicate predicateWithBlock: ^BOOL(id obj, NSDictionary *bind){        
    NSDictionary *data = (NSDictionary*)obj;

    // use 'filter' and implement your logic and return YES or NO
}];

[dataSet filteredArrayUsingPredicate:filterBlock];

可以根据需要重新排列,也许可以在自己的方法中重新排列。