Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

CoreData fetch with NSSortDescriptor by count of to-many relationship

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.

like image 745
DiscDev Avatar asked Dec 11 '13 22:12

DiscDev


1 Answers

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.

like image 56
Wain Avatar answered Sep 21 '22 00:09

Wain