【问题标题】:CoreData NSPredicate with two one-to-many relations具有两个一对多关系的 CoreData NSPredicate
【发布时间】:2013-02-07 23:47:10
【问题描述】:

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

类别 > 信息 > 组。

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

关于我可以做的信息

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

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

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

但我需要在类别级别编写谓词。我在假设我的数据集中的信息足够大以至于我无法将它们全部提取并处理它们以找到我的类别的假设下进行编程。我想创建一个谓词,它只会根据用户的组获取与用户相关的类别。

感谢您的帮助!

【问题讨论】:

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


    【解决方案1】:

    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"];
    

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多