Ian Kohlert
Ian Kohlert

Reputation: 514

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

Upvotes: 0

Views: 707

Answers (1)

Ian Kohlert
Ian Kohlert

Reputation: 514

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

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

Upvotes: 1

Related Questions