I am trying to sort an array by the number of times a given value is present for a given attribute.
To do this, I am using the following code:
NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] initWithKey:@"title.@count" ascending:NO];
NSArray *descriptors = [[NSArray alloc] initWithObjects:sortDescriptor, nil];
NSArray *sortedArray = [results sortedArrayUsingDescriptors:descriptors];
However, while the code compiles, at runtime it is giving the error:
'[<__NSCFNumber 0xb00000000004e293> valueForUndefinedKey:]: this class is not key value coding-compliant for the key @count.'
What am I doing wrong?
Edit:
The array in question actually consists of results from a core data fetch as follows:
self.managedObjectContext = [Model sharedInstance].managedObjectContext;
[fetchRequest setPredicate:pred];
// fetchRequest.resultType = NSDictionaryResultType;
NSArray<Articles*> *results = [self.managedObjectContext executeFetchRequest:fetchRequest
error:&error];
if ([results count]>=1) {
You can use +\[NSSortDescriptor sortDescriptorWithKey:ascending:comparator:\]
. That takes a block that can implement any algorithm you want. You can create an NSCountedSet
from [results valueForKey:@"title"]
before the sort operation and have the comparator block capture that. That way, you have an easy and cheap way to get the count of a given object's title. The issue is how to regenerate that counted set if/when the objects change (if they can).