NSPredicate与核心数据 [英] NSPredicate with Core Data

查看:87
本文介绍了NSPredicate与核心数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经浏览了苹果文档和SO,但我找不到这个简单的代码。

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.

这是我的数据模型中选择公司时处理产品更新的方法。它使用产品视图控制器的标题,因为该属性在didSelectItemAtIndexPath中分配了公司名称。

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];
 }

问题是此数组始终返回0个元素。我知道我有一个名为iPhone的产品,制造商是苹果。因此,它必须是谓词生成不正确的SQL。

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?

推荐答案

谓词与SQL并不完全相同,但是您可以通过添加 -com.apple.CoreData.SQLDebug 1 。

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.

此外,谓词格式为已记录。您问题的简短答案是 John 说:使用 CONTAINS 而不是LIKE。

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

这篇关于NSPredicate与核心数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆