Search code examples
iphonecore-datansfetchrequestkvc

Core data fetch: Sort by relationship count


I am trying to fetch an entity with the lowest count in one of it's relationships. The entity is called Solution, and this has a to-many relationship called gamesFeaturedIn which links to a Game object. So I am doing this (using the RestKit convenience methods):

Solution* lowestPlayedSolution = [Solution findFirstWithPredicate: nil sortedBy: @"gamesFeaturedIn.@count" ascending: NO];
NSUInteger lowestPlayedCount = [lowestPlayedSolution.gamesFeaturedIn count];

An this throws the error:

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

I have found a few posts with similar questions several years ago. Maybe things have changed and the old posts don't give any definite answers to how I can do this without fetching all the objects into memory and performing the calculation manually. Anyone?

EDIT: The core data store is SQLite backed, so I can not use transient properties to sort.


Solution

  • Sorry to break you the bad news, but things have not changed, at least in iOS5. There are mostly two workarounds, both rather non-elegant.

    1. The one you mentioned, you do the sorting afterwards in-memory.
    2. You create a non-transient property to store the count and update it each time you add or remove an item in the relationship.