Search code examples
swiftcore-datafetchpredicate

Fetch predicate: get all items with no relationship items from Core Data


I have an Entity called Group. Which has a to-many relationship to Group called parentGroup.

I want to query CD for all top level groups. (Ones that don't have a parent group).

I can't figure out what the predicate should be. I have tried:

fetch.predicate = NSPredicate(format: "parentGroup" == nil)

NSPredicate(format: "%K == nil", #keyPath(Group.parentGroup))

NSPredicate(format: "parentGroup" == %@, nil)

An old Obj-C post on a similar topic that didn't work: iPhone SDK Core Data: Fetch all entities with a nil relationship?

Thanks


Solution

  • Here is the solution. The other predicates were failing because it was a to-many relationship.

    fetch.predicate = NSPredicate(format: "parents.@count == 0")