Core Data SUBQUERY和NSFetchedResultsController的Keypath错误

如果这是重复的道歉,20分钟的搜索没有产生这种确切的情况或解决方案。

我有一个核心数据堆栈,有三个类XClassYClassZClassXClass有一对多的关系。 YClassZClass一对多的关系。

使用XClass的实例,我正在尝试获取至少1个YClass至少有1个ZClass所有XClass实例。

我的谓词定义如下:

 // ...stuff NSFetchRequest * fetchRequest = [NSFetchRequest new]; NSEntityDescription * entity = [NSEntityDescription entityForName:NSStringFromClass([XClass class]) inManagedObjectContext:managedObjectContext]; fetchRequest.entity = entity; fetchRequest.predicate = [NSPredicate predicateWithFormat:@"0  0).@count"]; // ..instantiate NSFetchedResultsController and perform fetch 

这会导致致命的exception消息: Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: 'Keypath containing KVC aggregate where there shouldn't be one; failed to handle $y.zObjects.@count' Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: 'Keypath containing KVC aggregate where there shouldn't be one; failed to handle $y.zObjects.@count'

在其他地方,我已成功使用谓词[NSPredicate predicateWithFormat:@"zObjects.@count > 0"];获取YObject实例[NSPredicate predicateWithFormat:@"zObjects.@count > 0"];

有人能指出我做错了吗? 非常感谢你。

当您在SUBQUERY的谓词字符串中使用集合运算符时,似乎NSPredicate会猛烈反对。 您似乎无法对子查询谓词中的集合进行操作。 这是除非变量表示谓词中的集合。

BAD: SUBQUERY(yObjects, $y, $y.zObjects == NIL) > 0

OK: SUBQUERY(yObjects, $y, SUBQUERY($y.zObjects $z, $z == NIL) > 0) > 0

以下表达式将所有非零对象添加到SUBQUERY返回的过滤集合中。 换句话说,返回的集合将包含具有ZClass实例的XClass的所有实例。

 [NSPredicate predicateWithFormat:@"yObjects.@count > 0 AND (SUBQUERY(yObjects, $y, (SUBQUERY($y.zObjects, $z, $z != NIL).@count > 0)).count > 0)"];