NSPredicate过滤到具有子对象属性的许多

时间:2013-11-27 06:25:21

标签: ios objective-c core-data nspredicate

我认为这是一个简单的问题。我试图过滤一些核心数据,其中我有一个Parent对象,该对象与子对象具有多对多的关系,并且该子对象具有字符串id。我想得到没有子对象具有特定id的所有父对象。

我尝试!(ANY... LIKE)以及!(ANY..==)NONE使用了喜欢和==和ALL children.id != otherid

我的查询如下:

NSFetchRequest* fetchRequest = [NSFetchRequest fetchRequestWithEntityName:@"Parent"];

NSPredicate* predicate = [NSPredicate predicateWithFormat:@"NONE children.id LIKE %@",otherID];
[fetchRequest setPredicate: predicate];
NSError* error;
NSArray* allParents = [[DataManager context] executeFetchRequest:fetchRequest error:&error];
//sanity check the predicate
for (Parent* p in allParents) {
    for (Child* c in p.children) {
        if([c.id isEqualToString:otherID]){
            NSLog(@"PREDICATE FAIL!");
        }
    }
}

我错过了NSPredicate的东西吗? CoreData是否允许这种类型的过滤?更好的解决方案?

1 个答案:

答案 0 :(得分:2)

我发现了一个类似的问题,虽然不是很明显。事实证明答案是棘手的SUBQUERY。这就是我追逐的原因:

NSPredicate Aggregate Operations with NONE

以及关于SUBQUERY的更开放的解释:

http://funwithobjc.tumblr.com/post/2726166818/what-the-heck-is-subquery

结果谓词是:

//in children get a $child and group all the $child objects together
//where the ids match, if that groups count is 0 we know 
//the parent has no child with that id
[NSPredicate predicateWithFormat:
   @"SUBQUERY(children, $child, $child.id == %@).@count == 0",objectId];