CoreData fetch with NSSortDescriptor by count of to-many relationship

Viewed 5469

I have 2 CoreData entities (Person, Pet) with the following relationship:

A Person can have multiple Pets. So, there is a To-Many relationship from Person->Pet.

I want to fetch all Persons, sorted by the count of Pets that they have where the person with the most Pets is first, and the person with the fewest Pets is last.

When fetching a list of Persons, I tried using an NSSortDescriptor like the following:

[NSSortDescriptor sortDescriptorWithKey:@"pets.count" ascending:NO]

I thought that the "pets" property on a "person" would allow me to use the count property of NSSet to sort. Alas, CoreData complains with this error:

Fetch exception to-many key not allowed here

Is this a completely wrong approach? How am I supposed to do something like this with a CoreData fetch?

Thanks in advance for your help.

4 Answers

I also need to do the same thing but in Swift. I just to follow:

  1. Fetch the request from CoreData without 'count' key-value.
  2. I performed sort (high order function) on the fetched result.
allCategory.sort { (category1, category2) -> Bool in
            return category1.tasks?.count > category2.tasks?.count
        }

This is working for me.

Related