I am fetching data from Core Data
storage using an NSFetchRequest
and store that data in an array
- all works great. As a next step, I want to sort that array
using NSSortDescriptors
like so:
array = [array sortedArrayUsingDescriptors:[NSArray arrayWithObjects:
[NSSortDescriptor sortDescriptorWithKey:@"score" ascending:NO],
[NSSortDescriptor sortDescriptorWithKey:@"score" ascending:NO comparator:^NSComparisonResult(id obj1, id obj2) {
if ([[[array objectAtIndex:[obj2 integerValue]] valueForKey:@"lessImportantItems"] containsObject:[array objectAtIndex:[obj1 integerValue]]]) {
return (NSComparisonResult)NSOrderedAscending;
} else {
return (NSComparisonResult)NSOrderedDescending;
}
}],
[NSSortDescriptor sortDescriptorWithKey:@"createdAt" ascending:NO], nil]];
The problem I have is that the NSComparator
block in the second NSSortDescriptor
isn't called (I tried to NSLog
). To give some background to my data structure, here's the relevant Core Data
object graph section:
What the application does is it compares items with one another. As a first step, the winner in a paired comparison gets a score
increment. But also I mark a paired priority, i.e. I add a one-to-many lessImportantItems
relationship from the winner to the loser. So, in my array I first try to sort by score
, and then, when score
s are equal, I also try and sort by paired priority.
Maybe it's because I use score
as comparator key
twice in a row? But, on the other hand, NSComparator
does not allow a relationship
to be passed as a key
either.
I can't seem to crack this one. Anyone has any ideas? Or perhaps I should take a different approach to sorting?