Reputation: 6589
I know you can do something like [..."SELF.some_id == [c] %d AND SELF.some_id == [c] %d", id1, id2], but I need more than this. Is there a way to do this without building a string.
For example...
NSArray *arrayOfWantedWidgetIds = @[1,3,5,6,9,13,14,16];
NSMutableArray *allWidgets = [[WidgetManager sharedWidget] getAllWidgets];
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"SELF.widget_id ==[c] %d", arrayOfWantedWidgetIds]; //obviously we can't do this, it won't accept an array of IDS for %d
[allWidgets filterArrayUsingPredicate:predicate];
How can I achieve something like this? Another way... if I looped this, and made individual predicates for each value in arrayOfWantedWidgetIds, and then add all the individual predicates into an array... this doesn't help either as filterArrayUsingPredicate only accepts an NSPredicate. Not an array of them.
Upvotes: 2
Views: 69
Reputation: 294
Look at the in operator
NSArray *idList = @[@1,@2,@3,@5,@7];
NSMutableArray *widgetList = [[NSMutableArray alloc] init];
for (int i=0; i<20; i++) {
[widgetList addObject:[[widgets alloc] init]];
}
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"SELF.widget_id in %@",idList];
NSLog(@"%@",[widgetList filteredArrayUsingPredicate:predicate].debugDescription);
Upvotes: 0
Reputation: 726479
You cannot pass an array to the predicate API like that. However, you can pass an array of IDs, and use the IN
operator, which should be sufficient in your specific case:
NSArray *arrayOfWantedWidgetIds = @[@1, @3, @5, @6, @9, @13, @14, @16];
NSMutableArray *allWidgets = [[WidgetManager sharedWidget] getAllWidgets];
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"SELF.widget_id IN %@", arrayOfWantedWidgetIds];
[allWidgets filterArrayUsingPredicate:predicate];
You can also construct a composite predicate with NSCompoundPredicate
, but this is unnecessary in this situation.
Upvotes: 5