2

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.

2 Answers 2

5

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.

1
  • 2
    You can also group multiple predicates with NSCompoundPredicate
    – thelaws
    Feb 12, 2015 at 18:55
0

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.