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.
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;
}
)
Only IN
needed:
NSArray * desiredIDs = @[@1, @2, @3, @4, @5];
NSString * predicateFormat = [NSString stringWithFormat:@"SELF.itemID IN %@", desiredIDs];
...
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With