Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get all items with NSPredicate CONTAINS IN array

I have an array of objects and each has an id, and i want to get all items where item.objectID contains in an array of ids, how can i get that result ?

What i tried to do but i have an error on creating predicateWithFormat: Unable to parse the format string:

NSString *predicateFormat = [NSString stringWithFormat:@"SELF.itemID CONTAIN IN (1,2,3,4,5,6,7,8)"];
NSPredicate *predicate = [NSPredicate predicateWithFormat: predicateFormat];
filteredData = [localData filteredArrayUsingPredicate:predicate];

I just what to avoid this:

NSString *predicateFormat = [NSString stringWithFormat:@"SELF.itemID = 1 OR SELF.itemID = 2 OR SELF.itemID = 3"];
NSPredicate *predicate = [NSPredicate predicateWithFormat: predicateFormat];
filteredData = [localData filteredArrayUsingPredicate:predicate];

because there is other condition to add for filter.

like image 936
Constantin Saulenco Avatar asked May 14 '15 12:05

Constantin Saulenco


2 Answers

You almost had it :)

    NSArray *objects = @[
        @{
            @"itemID" : @1
        },
        @{
            @"itemID" : @2
        },
        @{
            @"itemID" : @3
        },
        @{
            @"itemID" : @4
        },
        @{
            @"itemID" : @5
        }
    ];

    NSArray *idsToLookFor = @[@3, @4];
    NSPredicate *predicate = [NSPredicate predicateWithFormat:@"itemID IN %@", idsToLookFor];
    NSArray *result = [objects filteredArrayUsingPredicate:predicate];

    NSLog(@"result: %@", result);

And if you do not want to pass in any array, but write the predicate "in hand", the syntax would be:

NSPredicate *predicate = [NSPredicate predicateWithFormat:@"itemID IN { 3, 4 }"];

And the result will be:

result: (
        {
        itemID = 3;
    },
        {
        itemID = 4;
    }
)
like image 148
Steffen D. Sommer Avatar answered Nov 15 '22 19:11

Steffen D. Sommer


Only IN needed:

NSArray * desiredIDs = @[@1, @2, @3, @4, @5];
NSString * predicateFormat = [NSString stringWithFormat:@"SELF.itemID IN %@", desiredIDs];
...
like image 36
Kjuly Avatar answered Nov 15 '22 17:11

Kjuly