如何使用 NSPredicate 来过滤核心数据关系?

发布于 2024-09-18 08:14:37 字数 564 浏览 7 评论 0原文

假设我有“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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

梦幻之岛 2024-09-25 08:14:37

由于您与子对象存在一对多关系,因此 objsubs 属性返回一个集合而不是单个对象。要查询集合,您需要使用 SUBQUERY。

子查询的形式如下:

SUBQUERY(collection, $individualCollectionItem, expression-with-collection-item)

在这种情况下,您需要类似的东西

SUBQUERY(subs,$s,$s.propertyB==%@) AND SUBQUERY(subs,$s,$s.propertyC!=NULL)

Since you have a to-many relationship with the sub object, the subs property of obj returns a set instead of a single object. To query the set, you need to use a SUBQUERY.

Subqueries have the form:

SUBQUERY(collection, $individualCollectionItem, expression-with-collection-item)

in this case you would want something like

SUBQUERY(subs,$s,$s.propertyB==%@) AND SUBQUERY(subs,$s,$s.propertyC!=NULL)
咽泪装欢 2024-09-25 08:14:37

解决方案似乎是:

[NSPredicate predicateWithFormat:@"propertyA == %@ AND (SUBQUERY(sub, $s, $s.propertyB == %@ AND $s.propertyC == %@).@count != 0)",  propertyAvalue, propertyBvalue, propertyCvalue];

最后的值是您希望各种属性等于的值。

The solution seems to be:

[NSPredicate predicateWithFormat:@"propertyA == %@ AND (SUBQUERY(sub, $s, $s.propertyB == %@ AND $s.propertyC == %@).@count != 0)",  propertyAvalue, propertyBvalue, propertyCvalue];

where the values at the end are the values you want the various properties to be equal to.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文