2010-09-27 40 views
0

鑑於下列核心數據模型中定義的實體:因此,在ANSPredicate爲一對多的關係,其中一個關係(NSSet中)必須包含在一個NSArray

-> : 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 

@property (nonatomic, retain) NSSet *Bs; 

在類B

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

假設我有一個NSArray *myArray包含ing (Bj, Bk)

我要的是獲取屬於Ax和涉及BjBk所有B的:

以下作品的代碼,但完全是醜陋的,因爲我有硬編碼NSPredicate基礎對數(這裏是2,但它可能是10左右)的陣列中的B的:

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

我怎麼可以重寫謂詞,使其更通用?它必須是那麼明顯,但我沒有看到它......

回答

2

是否

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

你期待什麼?我不確定(並且遠離我的OS X框)此謂詞是否可轉換爲SQL核心數據SQLite引擎。您可能需要一個SUBQUERY表達:

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

這裏假定myArray的項目是獨一無二的。

+0

Thx爲快速響應。你的第一個解決方案引發一個Exception:不支持的謂詞(null)。第二部作品(不得不解決@count和失蹤)。但速度很慢。我的硬編碼解決方案大約需要0.012秒,而子查詢解決方案大約需要10秒... – codeclash 2010-09-27 21:03:50

+0

不幸的是,您所要求的(通用解決方案)與對關係引擎的高效SQL查詢間接衝突。我認爲你必須選擇一個或另一個。完全是什麼語法錯誤?我會糾正這個帖子。 – 2010-09-27 21:09:41

+0

呵呵。你是否已經修改了查詢?或者我是否將您的解決方案與SUBQUERY文檔中的解決方案混合在一起?我的不好:你的解決方案完美地工作,對不起,它很有用,平均時間爲0.000016秒!我想我把你的解決方案與文檔中的一個混合在一起:NSPredicate * predicate = [NSPredicate predicateWithFormat:@「A ==%@ and(SUBQUERY(Bs,$ x,$ x IN%@)。@ count == Bs。@ count)「,Ax,myArray,myArray.count];這個非常糟糕,平均需要10秒左右。因爲Bs。@ count!非常感謝,拯救了我的一天! – codeclash 2010-09-27 21:28:35

相關問題