Ios – CoreData fetch with NSSortDescriptor by count of to-many relationship

core-dataiosobjective c

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.

Best Answer

Try using collection operators:

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

This can't be applied directly though (to a fetch request), you need to execute the fetch and then run the sort on the result array (sortedArrayUsingDescriptors:).

If you want to sort while fetching, you would need to add a (non-transient) attribute to the entity which holds the count number.

Related Topic