2012-10-12 40 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

相关问题