核心数据:谓词中的对象
在我的核心数据对象模型中,我有 3 个具有适当关系的实体,以便 MyObject 可以有许多 MyObjectProperties,并且每个属性可以有一个 MyObjectPropertyImage。
给定一个 myObject 我想获取所有图像。
我尝试使用以下谓词来执行此操作,但是我得到一个空数组:
[NSEntityDescription entityForName:@"MyObjectPropertyImage" inManagedObjectContext:managedObjectContext];
[NSPredicate predicateWithFormat:@"ANY myObjectProperty.myObject == %@", myObject];
有什么想法吗?
In my core data object model I have 3 entities with appropriate relationships so that MyObject can have many MyObjectProperties, and each property can have one MyObjectPropertyImage.
Given a myObject I want to fetch all the images.
I try to do it using the following predicate, however I get an empty array:
[NSEntityDescription entityForName:@"MyObjectPropertyImage" inManagedObjectContext:managedObjectContext];
[NSPredicate predicateWithFormat:@"ANY myObjectProperty.myObject == %@", myObject];
Any ideas?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
使用核心数据时,最好将实体视为:对象图中的实体,而不是数据库中的表。因此,您不需要使用谓词来获取与其他实体相关的实体。相反,使用模型中定义的关系来导航对象图。要获取与
myObject
相关的所有图像:请注意,如果您的
myObject
实体的对象图未加载到内存中,这可能会触发额外的数据库访问。为了避免这种情况,请确保在myObject
的提取请求中设置预提取关系键路径。我希望这有帮助...
When working with Core Data it's best to think of your entities as just that: entities in an object graph, instead of tables in a database. Therefore, you don't need to fetch entities related to others using a predicate. Instead, navigate the object graph using the relationships defined in the model. To get all the images related to
myObject
:Note that this may trigger additional trips to the database if your object graph is not loaded in memory for your
myObject
entity. To avoid that, make sure you set the pre-fetching relationship keypaths in your fetch request formyObject
.I hope this helps...
由于您手头有一个
MyObject
实例,并且它具有myObjectProperties-->ObjectProperty-->>PropertyImages
的关系路径,因此您只需要遍历这些关系即可。使用valueForKeyPath:
可以很容易地做到这一点:(
注意:我可能你的属性名称错误,但你可以明白这个想法。)
作为一般规则,当图表中有可用的对象时,你永远不会获取。您获取与谓词匹配的对象的“挑选线程”,然后按照与相关对象的线程/关系查找所有相关对象。
Since you have a
MyObject
instance in hand and it has the relationship path ofmyObjectProperties-->ObjectProperty-->>PropertyImages
you just need to traverse the relationships. It's easy to do this withvalueForKeyPath:
Thusly:
(Note: I might have your attribute names wrong but you can get the idea.)
As general rule, you never fetch when have an object from the graph available. You fetch to "pick out thread" of objects matching the predicate and then to find all related objects you follow the thread/relationships to the related objects.