Search code examples
iosswiftcore-datanspredicate

Core Data nested array count


I have nested to-many relations in core data: A -> B -> C, where A has multiple objects of B, and B has multiple objects of C.

Now, I'm trying to fetch all objects A which have zero related objects of C, no matter how many objects of B are in between.

I tried this predicate:

NSPredicate(format: "SUBQUERY(arrayOfB, $b, $b.arrayOfC.@count == 0).@count > 0")

But it gives me this error:

'NSInvalidArgumentException', reason: 'Keypath containing KVC aggregate where there shouldn't be one; failed to handle $b.arrayOfC.@count'


Solution

  • Try using the alternative format for count expressions:

    NSPredicate(format: "SUBQUERY(arrayOfB, $b, count:($b.arrayOfC) > 0).@count == 0")
    

    Note that I think your conditions are the wrong way around: you want a zero count for (arrayOfB's where arrayOfC is has non-zero members).