NSPredicate for to-many关系,其中关系(NSSet)必须包含在NSArray中定义的实体 [英] NSPredicate for to-many relationship, where a relationship (NSSet) must contain Entities defined in an NSArray
问题描述
给定以下核心数据模型:
Given the following Core Data Model:
-> : 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;
假设我有一个 NSArray * myArray
(Bj,Bk)
。
我想要的是获取属于的所有
,并与 B
Ax Bj
和 Bk
:
What I want is to fetch all B
's which belong to Ax
and are related to Bj
and Bk
:
下面的代码工作,但是完全丑陋,因为我必须硬编码的NSPredicate基于数字(这里是2,但可能是10左右)的 B
在数组中:
The code below works, but is completely ugly, since I have to hardcode the NSPredicate based on the number (here it's 2, but it could be 10 or so) of B
's in the array:
NSEntityDescription *fetchedEntity = [NSEntityDescription entityForName:@"B" inManagedObjectContext:self.managedObjectContext];
[NSPredicate predicateWithFormat:@"A == %@ and (Bs contains %@) and (Bs contains %@)", Ax, [myArray objectAtIndex:0], [myArray objectAtIndex:1]];
如何重写谓词以使其更通用?必须非常明显,但我只是看不到它...
How can I rewrite the predicate so that it is more generic? It must be so obvious, but I just don't see it...
推荐答案
是否
[NSPredicate predicateWithFormat:@"A==%@ AND (ALL %@ IN Bs)", Ax, myArray];
做你期望的?我不确定(和远离我的OS X框)这个谓词是否可以翻译为SQL的Core Data SQLite引擎。您可能需要 SUBQUERY 表达式:
do what you expect? I am not sure (and away from my OS X box) whether this predicate is translatable to SQL for the Core Data SQLite engine. You may need a SUBQUERY expression:
[NSPredicate preidcateWithFormat:@"A==%@ and SUBQUERY(Bs, $x, $x IN %@).@count == %d", Ax, myArray, myArray.count];
这假设 myArray
中的项目唯一。
这篇关于NSPredicate for to-many关系,其中关系(NSSet)必须包含在NSArray中定义的实体的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!