Reputation: 39052
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.
Upvotes: 12
Views: 5826
Reputation: 2142
I also need to do the same thing but in Swift. I just to follow:
allCategory.sort { (category1, category2) -> Bool in
return category1.tasks?.count > category2.tasks?.count
}
This is working for me.
Upvotes: 0
Reputation: 119021
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.
Upvotes: 16
Reputation: 8988
Take a look at this answer https://stackoverflow.com/a/20317087/2567126
Basically you create a persistent property on the NSManagedObject and update the property count any time a child object is added or removed from the relationship.
Upvotes: 0