【问题标题】:NSPredicate for to-many relationship, where a relationship (NSSet) must contain Entities defined in an NSArray对多关系的 NSPredicate,其中关系(NSSet)必须包含在 NSArray 中定义的实体
【发布时间】:2011-04-17 23:27:01
【问题描述】:

给定以下核心数据模型:

-> : to-one releationship  
->>: to-many relationship

Entity A ->> Entity B 
Entity B -> A // each B belongs to exactly one A  
Entity B ->> B // a B can be related to other B's

所以在课堂上A

@property (nonatomic, retain) NSSet *Bs;

在课堂B

@property (nonatomic, retain) A *A;  
@property (nonatomic, retain) NSSet *Bs; 

假设我有一个包含(Bj, Bk)NSArray *myArray

我想要的是获取所有属于Ax并与BjBk相关的B

下面的代码可以工作,但非常难看,因为我必须根据数组中B 的数量(这里是 2,但可能是 10 左右)对 NSPredicate 进行硬编码:

NSEntityDescription *fetchedEntity = [NSEntityDescription entityForName:@"B" inManagedObjectContext:self.managedObjectContext];
[NSPredicate predicateWithFormat:@"A == %@ and (Bs contains %@) and (Bs contains %@)", Ax, [myArray objectAtIndex:0], [myArray objectAtIndex:1]];

如何重写谓词使其更通用?一定很明显,但我就是没看到...

【问题讨论】:

    标签: iphone objective-c core-data nspredicate


    【解决方案1】:

    [NSPredicate predicateWithFormat:@"A==%@ AND (ALL %@ IN Bs)", Ax, myArray];
    

    做你期望的?我不确定(并且远离我的 OS X 机器)这个谓词是否可以转换为 Core Data SQLite 引擎的 SQL。你可能需要一个SUBQUERY 表达式:

    [NSPredicate preidcateWithFormat:@"A==%@ and SUBQUERY(Bs, $x, $x IN %@).@count == %d", Ax, myArray, myArray.count];
    

    这假定myArray 中的项目是唯一的。

    【讨论】:

    • 感谢您的快速响应。您的第一个解决方案引发异常:不支持的谓词(null)。第二个作品(必须修复 @count 和 missing )。但这很慢。我的硬编码解决方案大约需要 0.012 秒,而子查询解决方案大约需要 10 秒...
    • 不幸的是,您所要求的(一般解决方案)是与针对关系引擎的有效 SQL 查询的间接冲突。我认为你必须选择其中一个。语法错误到底是什么?我会更正帖子。
    • 嗯。您是否已经更正了查询?还是我将您的解决方案与 SUBQUERY 文档中的解决方案混合在一起?我的错:您的解决方案完美运行,抱歉,它很糟糕,平均时间是 0.000016 秒!我想我将您的解决方案与文档中的一个混合在一起: NSPredicate *predicate = [NSPredicate predicateWithFormat:@"A == %@ and (SUBQUERY(Bs, $x, $x IN %@).@count == Bs.@计数)”,斧头,myArray,myArray.count];这个真的很糟糕,平均需要10秒左右。因为 Bs.@count!非常感谢,拯救了我的一天!
    猜你喜欢
    • 2018-04-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-06-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多