views:

458

answers:

3

Say I have an parent entity, each of which have a number of children. I want to get all the parents sorted by their number of children. Something similar to the following pseudo code:

NSEntityDescription * entity = [NSEntityDescription entityForName:@"Parent" inManagedObjectContext:managedObjectContext];

[[NSSortDescriptor alloc] initWithKey:@"children.count" ascending:NO];
//Execute request

Is there a way construct a fetch like this using core data? If there is no way to do this will sorting using sortedArrayUsingSelector: loose the benefits of _PFBatchFaultingArray batch size?

Thanks, Ben

+3  A: 

Your query would work, but (assuming children is faulted) would use key-value coding methods on the children property, which in turn would fire the fault (see the NSManagedObject docs for a list of methods that fire faults, and a discussion of this behavior), so you'd lose the performance benefits of batching and faulting.

You might consider maintaining a derived attribute on your parent entity (call it childrenCount) that reflects the number of children related to the parent, if this is feasible for your situation. It's not the cleanest solution, but if you keep it as an NSNumber in the parent entity you'd have access to it even if children is faulted, and you can sort on it directly.

Tim
The KVC `@count` would be performed on the `NSSet` not the objects within that `NSSet` and therefore does not cause the faults to fire.
Marcus S. Zarra
It does cause the fault to fire, since Core Data doesn't fault each object individually - it faults the set itself (or rather, a concrete subclass of NSSet). See http://developer.apple.com/iphone/library/documentation/Cocoa/Conceptual/CoreData/Articles/cdFaultingUniquing.html#//apple_ref/doc/uid/TP30001202, under "Faulting Limits the Size of the Object Graph".
Tim
A: 
NSEntityDescription * entity = [NSEntityDescription entityForName:@"Parent" 
                                           inManagedObjectContext:moc];

[[NSSortDescriptor alloc] initWithKey:@"children.@count" 
                            ascending:NO];

The KVO accessor will not fire the faults on the children but will perform the sort.

Marcus S. Zarra
A: 

I am doing something very similar to what is suggested above to sort by the count of a child but keep running into:

'Keypath containing KVC aggregate where there shouldn't be one; failed to handle children.@count'

Any idea what could be causing this?

avenged