It's a long standing problem when using Core Data to-many-relationships that it is very hard to sort a fetch request using NSSortDescriptor
on a Parent
entity based on the number of children
are in a one-to-many relationship to a Child
entity. This is especially useful in combination with a NSFetchedResultsController
. Typically initializing the sort descriptor as:
NSSortDescriptor *sortByNumberOfChildren = [[NSSortDescriptor alloc] initWithKey:@"children.@count" ascending:NO];
results in an exception'Keypath containing KVC aggregate where there shouldn't be one; failed to handle children.@count
On iOS 6.1, I discovered a fix by adding the KVO accessor -countOf<Key>
as an attribute to my managed object model as an integer type. I did NOT implement anything for this attribute in my NSManagedObject
subclass, as all the magic seems to happen under the hood. (see https://mcmap.net/q/880400/-core-data-sorting-by-count-in-a-to-many-relationship).
However, this does not work on iOS 6.0. Here I found that adding the following method to your NSManagedObject
subclass resolves the problem:
- (NSUInteger)countOfChildren{
return [self.children count];
}
Adding both does not fix the problem in both SDKs. On the contrary, it breaks the fix.
Does anyone have a clue why this is happening and why there is a difference between both, eventhough there is no mention of changes to Core Data or Foundation between iOS 6.0 and iOS 6.1.
NSManagedObjectModel
? It's hard to see how that could even compile, let alone work. TheNSManagedObjectModel
does not have any relationships to other classes. – AmphictyonNSManagedObject
subclass also the second time around. I've corrected the mistake. – Deflocculate