Sort entity by subquery - NSSortdescriptor
I have 3 core data entities:
Entity A and Entity B and User which are related like
Entity A < ------ >> Entity B <<----- > User
I want to sort the entries in Entity A by the number of 开发者_如何学编程entries in entity B for that specific user.
I could do this:
- fetch all Entity A entries
- For each entry - fetch the number of Entity B entries for that entry and for the current user
- Count the number of entries for that Entity A entry store and then sort.
This though seems awfully stupid.
Is there anyway i could sort Entity A with a NSSortDescriptor perhaps by using a Subquery? Or if you know any other way i should solve this?
You can't sort on a collection operator so there is no way to us a sort descriptor to do what you want. Subqueries, like all predicates, simply find objects based on test, they don't sort them.
The easiest solution would be to add a transient attribute, say bCount
, to EntityA
. Then have the getter method return a count of related EntityB
objects:
-(NSNumber *) bCount{
return [NSNumber numberWithInt:[self.bs count]];
}
Then sort your EntityA
objects on the bCount
key.
精彩评论