0
votes

I've look through apple documentation and SO and I cannot find this simple code.

I will accept any down votes I get for such a question, but what is the predicate string that will return a given entity where that entity's property is equivalent to a given string.

I have company and product entities. At the moment, they are simple. Company has name and some other attributes. Product has manufacturer and some other attributes.

I want to do a fetch for all products where the products manufacturer attribute is equivalent to the name of the company that was selected in the company's view controller.

Here is the method in my data model that handles updating the products when a company is selected. It uses the title of the product view controller because that property is assigned the company name in didSelectItemAtIndexPath.

-(void)updateProducts {

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

NSEntityDescription *entProd = [NSEntityDescription entityForName:@"Product" inManagedObjectContext:self.context];

[reqProd setEntity:entProd];

NSString *companyToFilter = self.productsViewController.title;

reqProd.predicate = [NSPredicate predicateWithFormat:@"manufacturer like %@", companyToFilter];

NSError *errorProd = nil;

self.productList = [self.context executeFetchRequest:reqProd error:&errorProd];
 }

The problem is that this array always returns 0 elements. I know I have a product named iPhone who's manufacturer is apple. Therefore, it must be the predicate that is generating inaccurate SQL.

Again, I spent way too much time search for the answer to no avail. would somebody help me and explain the proper string for the predicate or direct me to the proper documentation?

2

2 Answers

0
votes

The semi-equivalent of the SQL LIKE operator in CoreData is BEGINSWITH for prefixes, ENDSWITH for suffixes, or CONTAINS for matches anywhere in the string.

[NSPredicate predicateWithFormat:@"manufacturer CONTAINS %@", companyToFilter]

You can also write CONTAINS[cd] to indicate "case and diacritic insensitive", or just CONTAINS[c] or CONTAINS[d].

0
votes

Predicates are not exactly like SQL, but you can get it to output the SQL being used by adding -com.apple.CoreData.SQLDebug 1 in the startup options.

Also, the predicate format is documented. The short answers to your question is as John says: use CONTAINS instead of LIKE.