如何使用 NSPredicate 来过滤核心数据关系?
假设我有“obj”类型的核心数据对象,该对象具有属性“propertyA”,并且与具有两个属性“propertyB”和“propertyC”的“sub”类型的对象存在一对多关系。
我想获取 propertyA 等于某个值的所有对象以及设置了 propertyB 和 propertyC 的子对象。
如果只是 propertyA 和 propertyB,我会这样做。
[NSPredicate predicateWithFormat:@"ANY sub.propertyB = %@ AND propertyA == %@", ...];
问题是我不知道如何添加第二个属性。我只想要至少有一个子对象具有这两个属性 true 的对象。我已经尝试过以下方法,但它不起作用:
[NSPredicate predicateWithFormat:@"ANY (sub.propertyB = %@ AND sub.propertyC) AND propertyA == %@", ...];
我已经在没有 ANY 的情况下尝试过,但这也不起作用。我该怎么做?
Say I have core data objects of type "obj" that has a property "propertyA" and a one-to-many relationship with an object of type "sub" that has two properties, "propertyB" and "propertyC".
I want to fetch all the objs that have propertyA equal to a value and a sub obj with propertyB and propertyC set.
If it was just propertyA and propertyB, I would do
[NSPredicate predicateWithFormat:@"ANY sub.propertyB = %@ AND propertyA == %@", ...];
The problem is that I can't figure out how to add in the second property. I want only the objs that have at least one sub that has the two properties true. I've tried the following, but it doesn't work:
[NSPredicate predicateWithFormat:@"ANY (sub.propertyB = %@ AND sub.propertyC) AND propertyA == %@", ...];
I've tried it without the ANY but that doesn't work either. How can I do this?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
由于您与子对象存在一对多关系,因此
obj
的subs
属性返回一个集合而不是单个对象。要查询集合,您需要使用 SUBQUERY。子查询的形式如下:
在这种情况下,您需要类似的东西
Since you have a to-many relationship with the sub object, the
subs
property ofobj
returns a set instead of a single object. To query the set, you need to use a SUBQUERY.Subqueries have the form:
in this case you would want something like
解决方案似乎是:
最后的值是您希望各种属性等于的值。
The solution seems to be:
where the values at the end are the values you want the various properties to be equal to.