Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Creating NSPredicate based on SQL IN() function for Core Data

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.

like image 941
atastrophic Avatar asked Jul 17 '13 05:07

atastrophic


1 Answers

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

like image 132
Anupdas Avatar answered Sep 28 '22 11:09

Anupdas