使用 NSPredicate 的多个关系访问值
这是我的核心数据模型:
Locations < --->>主题列表<< --->主题
实体具有以下属性:
位置
- 属性:名称
- 关系:主题列表
主题列表
- 关系:地点
- 关系:
主题 主题
- 属性:名称
- 关系:位置
我正在实体位置上运行提取,并且我只想提取主题中的名称属性等于特定值的值。根据我所读到的内容,我需要执行子查询。我已经按照下面的代码尝试了一些操作,但是我总是收到错误 无法解析格式字符串
[NSString stringWithFormat:@"SUBQUERY(ThemesList, $theThemes, $theThemes.Themes.Name LIKE %@)", @"a theme name"];
关于如何完成此操作的任何想法 - 我做错了什么?
谢谢
here is my core data model:
Locations < --- >> ThemesList << --- > Themes
The entites have the following attributes:
Locations
- Property: Name
- Relationship: ThemesList
ThemesList
- Relationship: Locations
- Relationship: Themes
Themes
- Property: Name
- Relationship: Locations
I am running a fetch on entity Locations and I want to only pull values where the name property in Themes is equal to a particular value. Based on what I've read, I need to do a subquery. I've tried something along the lines of the code below, but I always receive the error of Unable to parse the format string
[NSString stringWithFormat:@"SUBQUERY(ThemesList, $theThemes, $theThemes.Themes.Name LIKE %@)", @"a theme name"];
Any ideas on how I can accomplish this - what am I doing wrong?
Thanks
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
根据经验,您应该使用谓词获取正在测试的实体的对象,而不是完全从另一个实体开始并在谓词内遍历关系。遍历关系,尤其是谓词内的多对多关系,计算量大且速度慢。
相反,我建议针对
Theme
实体运行提取,然后仅向返回的Theme
对象询问其关联的Locations
对象。您的谓词将简化为:
然后使用集合运算符来查找位置对象:
As a rule of thumb, you should fetch the objects of the entity you are testing with the predicate instead of starting with another entity altogether and walking a relationship inside the predicate. Walking relationships, especially to-many relationships inside of predicates is computationally intensive and slow.
Instead, I would recommend running the fetch against the
Theme
entity and then just ask the returnedTheme
objects for their associatedLocations
objects.Your predicate would simplify to just:
Then use a collection operator to find the location objects:
您的问题是这样的:
$theThemes.Themes.Name
。解析器希望将其解析为变量表达式(因为它以$
开头),但是当遇到.
时,它将产生错误。事实证明,SUBQUERY 是不必要的。可以有效地完成相同的查询:
希望 Core Data 比 SUBQUERY 更容易处理它。
Your problem is this:
$theThemes.Themes.Name
. The parser will want to parse it as a variable expression (since it starts with a$
), but when it comes across the.
, it's going to produce an error.As it turns out, the
SUBQUERY
is unnecessary. That same query can be effectively done as:Hopefully Core Data will have an easier time handling that than the
SUBQUERY
.