2012-10-12 92 views
2

我有三個實體A,B,C.使用NSPredicate過濾對象在覈心數據

它們之間的關係是:A < - >> B,B < - >下進行。

A有一個叫'type'的屬性。 A和B的關係是a2b,B和C的關係是b2c。 c_array是C對象的列表。

我想要做的就是使用NSPredicate來過濾C和A的屬性'type'。

NSFetchRequest *fetchRequest = [[NSFetchRequest alloc]init]; 

NSEntityDescription *entity = [NSEntityDescription entityForName:@"A" inManagedObjectContext:managedObjectContext]; 
[fetchRequest setEntity:entity]; 

NSMutableArray *parr = [NSMutableArray array]; 

for (C *c in c_array) { 
    [parr addObject:[NSPredicate predicateWithFormat:@"ANY a2b.b2c = %@", c]]; 
} 

NSPredicate *predicate = [NSCompoundPredicate andPredicateWithSubpredicates:[NSArray arrayWithObjects:[NSCompoundPredicate orPredicateWithSubpredicates:parr], [NSPredicate predicateWithFormat:@"type = %i", 0], nil]]; 

[fetchRequest setPredicate:predicate]; 

但我得到的不是我的預期。所以我也試過其他的。

predicate = [NSPredicate predicateWithFormat:@"type=%i AND (0!=SUBQUERY(a2b,$a2b,$a2b.b2c IN %@)[email protected])", 0, c_array]; 

意外的結果再次發生!有人可以幫我嗎? T T

回答

0

聽起來像你想以相反的方式做到這一點。你已經有了C,並且根據你描述的關係,你的C類將擁有B屬性,而你的B類將擁有A屬性。因此,假如你使用c2bb2a這樣的事情應該工作:

NSPredicate *predicate = [NSPredicate predicateWithFormat:@"c2b.b2a.type == %@",[NSNumber numberWithInt:0]]; 

NSArray *result = [c_array filteredArrayUsingPredicate:predicate]; 

此外,我注意到你在你的謂語Atype屬性比較爲int。只需要尋找type==%i(其中i爲0)將返回所有在type中沒有值的對象。因此要麼將typeNSNumber對象相比較,要麼將type.intValue與int相比較。

+0

感謝您的回覆:)我通過逐行檢查解決了這個問題。當我添加B時,我發現我錯過了C和B之間的一種關係。對不起,我的愚蠢的錯誤。但你表示NSNumber問題,這對我很有幫助,謝謝。 – brianLikeApple

相關問題