I have a scenario where I must fetch multiple records from Core Data based on multiple values of a given column. A common SQL query for this purpose would be
SELECT * FROM suppliers
WHERE supplier_name in ('IBM', 'Hewlett Packard', 'Microsoft');
I have not been able to figure out how I'd use the native IN()
function for this purpose.
The way I am creating the NSPredicate
at the moment seems redundant and is as follows.
NSMutableArray *predicateArray = [NSMutableArray array];
[skus enumerateObjectsUsingBlock:^(NSString *sku, NSUInteger idx, BOOL *stop) {
[predicateArray addObject:
[NSString stringWithFormat:@"(AudioSKU == \"%@\")", sku]];
}];
NSString *predicateString = [predicateArray
componentsJoinedByString:@" OR "];
NSPredicate *predicate = [NSPredicate
predicateWithFormat:predicateString];
Is there a proper way to use NSPredciate or NSExpression for using IN
function of SQL? Please enlighten me.
There is a similar feature in NSPredicate
as well
NSArray *skus = @[];
NSPredicate *predicate = [NSPredicate
predicateWithFormat:@"AudioSKU IN %@",skus];
And also you cannot treat the predicate strings like usual strings. You cannot form an array of strings and use them for filtering. If there are multiple joins use the NSCompoundPredicate
.
A good reference Using NSPredicate to filter Data
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