Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

NSSortDescriptor and to-many relationships

I have two types of objections: locations and history items. I'm trying to fetch locations which are attached to any history item, so my fetch predicate for the location is "history.@count > 0", which works fine.

I'd also like to sort the location objects with an NSSortDescriptor by the date of their latest history item, which as far as I can make out would be "[email protected]", this however throws the following error:

*** Terminating app due to uncaught exception 'NSInvalidArgumentException',
    reason: 'Keypath containing KVC aggregate where there shouldn't be one;
    failed to handle [email protected]'

Halp plox?

like image 386
Joonas Trussmann Avatar asked Oct 05 '09 14:10

Joonas Trussmann


3 Answers

AFAIK, you must only use collection operators, described in the Key-Value Coding Programming Guide, for the key paths of your sort descriptors with collections (NSArray, NSSet, NSDictionary).

You must not use collection operators for the key paths of your sort descriptors with fetch requests (NSFetchRequest).

@kdbdallas correctly uses a collection operator to sort an NSArray. He is not using it to specify the sort descriptor of a fetch request.

It'd be sweet though if collection operators worked for specifying the key paths by which to sort fetch requests. Please submit this feature request at http://bugreport.apple.com/. The more it's reported, the more likely they'll support it.

like image 158
ma11hew28 Avatar answered Nov 06 '22 15:11

ma11hew28


Probably not the best solution, but you could always pull back the data and sort it after the fact. Have a look at Sorting and Filtering NSArray Objects.

like image 37
slf Avatar answered Nov 06 '22 17:11

slf


Since iOS 13 (and friends) you should be able to create a derived attribute called historyMaxTime with the derivation expression max:(history.time) and then set fetchRequest.sortDescriptors = @[[NSSortDescriptor sortDescriptorWithKey:@"historyMaxTime" ascending:NO]]

like image 44
numist Avatar answered Nov 06 '22 16:11

numist