NSPredicate 'OR' filtering based on an NSArray of keys

霸气de小男生 提交于 2019-12-03 13:01:13

The ANY operator of NSPredicate covers this:

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

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

Do this:

   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);

Works perfectly for me. Hope Helpful

Altough the question has been answered, you could also use block for more granularity:

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];

That could be rearranged as you want, maybe within its own method.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!