ios - 具有两个一对多关系的 CoreData NSPredicate

标签 ios core-data many-to-many nspredicate any

我有一个像这样的 CoreData 模型数据结构,用于根据用户所属的组限制信息:

类别<->>信息<->>组。

我有一个 NSSet 的 UserGroups 对象。我希望能够根据组对象的 NSSet 过滤类别,这样如果一个类别不包含任何在我的 NSSet 中有任何组的信息,我的谓词将不会返回它们。

我能做的信息

[NSPredicate predicateWithFormat:@"ANY groups in (%@)",groups];

对于类别,我尝试了以下方法,但只有一次崩溃:

[NSPredicate predicateWithFormat:@"ANY information.groups in (%@)",groups];

但我需要在类别级别编写谓词。我在编程时假设我的数据集中的信息足够大,以至于我无法将它们全部拉出并处理它们以找到我的类别。我想创建谓词,根据他/她的组仅获取与用户相关的类别。

感谢您的帮助!

最佳答案

Category 上的以下谓词应该有效(假设 information 是从 CategoryInformation 的对多关系):

[NSPredicate predicateWithFormat:@"SUBQUERY(information, $i, ANY $i.groups in %@).@count > 0",groups];

或者,您可以使用反向关系:

 // your set of Group objects:
 NSSet *groups = ...;
 // all Information objects that are related to any group object:
 NSSet *information = [groups valueForKey:@"information"] ;
 // all Category objects that are related to any information object:
 NSSet *categories = [information valueForKey:@"category"];

可以组合成

 NSSet *categories = [groups valueForKeyPath:@"information.category"];

此替代解决方案的一个缺点可能是它还在内存中创建了一组中间组。

关于ios - 具有两个一对多关系的 CoreData NSPredicate,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14763320/

相关文章:

ios - 将数据从 UIViewController 传递到 UISpiltView

ios - Xcode模拟器中相机的用途

ios - 为什么在应用程序重新启动或我执行 NSBatchDeleteRequest 两次之前不会删除条目?

javascript - Sequelize "include"不工作白色多对多关系

ios - 使用 AVFoundation 像在屏幕上一样捕获图像预览

objective-c - 如何在 iOS 4 上运行 iOS 5/ARC 项目

swift - 属性不会覆盖 swift5 中其父类(super class)的任何属性

ios - CoreData - 我什么时候保存?

c# - 如何在 Entity Framework 中查询具有 ID 数组的多对多关系

sql - 使用 SQL 和 Linq 的多对多关系( Entity Framework /实体)