Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using NSPredicate to match against a list of integers

I have a table with an integer field. I want to select all rows where that field contains any of a few different values.

I'm using this:

[NSPredicate predicateWithFormat:@"myIntValue IN {1,2,3,4}"]

but this only returns rows where myIntValue is 1.

What am I doing wrong?

like image 671
teedyay Avatar asked Apr 14 '11 11:04

teedyay


3 Answers

This works:

NSFetchRequest *request = [[NSFetchRequest alloc] init];

NSArray *idList = [NSArray arrayWithObjects:[NSNumber numberWithInt:1],
                                            [NSNumber numberWithInt:2],
                                            [NSNumber numberWithInt:3],
                                            [NSNumber numberWithInt:4],
                                            nil];
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"idealForId IN $IDLIST"];
request.predicate = [predicate predicateWithSubstitutionVariables:
    [NSDictionary dictionaryWithObject:idList forKey:@"IDLIST"]];
like image 190
teedyay Avatar answered Oct 13 '22 00:10

teedyay


Have you tried this?

NSPredicate *predicate = [NSPredicate predicateWithFormat:@"myIntValue IN %@",
[NSArray arrayWithObjects:@"1", @"2", @"3", @"4", nil]];

The documentation may be of use here.

like image 44
Tristan Warner-Smith Avatar answered Oct 13 '22 00:10

Tristan Warner-Smith


I don't know if this has changed since the question was originally posted but I get the exact same predicate from all three of these.

[NSPredicate predicateWithFormat:@"myIntValue IN {1, 2, 3, 4}"];

[NSPredicate predicateWithFormat:@"myIntValue IN {%d, %d, %d, %d}", 1, 2, 3, 4];

[NSPredicate predicateWithFormat:@"myIntValue IN %@", @[@1, @2, @3, @4]];

So no need to wrap everything in objects.

like image 21
trapper Avatar answered Oct 12 '22 23:10

trapper