我有一个我认为很简单的问题。我正在尝试过滤一些核心数据,其中我有一个父对象,该对象与子对象具有一对多关系,并且该子对象具有字符串 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 是否允许这种类型的过滤?更好的解决方案?
最佳答案
我发现了一个类似的问题,尽管不太明显。事实证明,答案是棘手的 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];
关于ios - NSPredicate 过滤器对多与子对象属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20235381/