APIs for sorting are generally capable to use an array of NSSortDescriptors
, not just one, so why not use them?
For example, NSArray
has a method called sortedArrayUsingDescriptors:
(note the plural form) which takes an array of NSSortDescriptor
objects.
So you can simply write this:
NSSortDescriptor *endCalYearSD = [NSSortDescriptor sortDescriptorWithKey:@"endCalYear" ascending:YES];
NSSortDescriptor *endMonthSD = [NSSortDescriptor sortDescriptorWithKey:@"endMonth" ascending:YES];
NSSortDescriptor *periodLenSD = [NSSortDescriptor sortDescriptorWithKey:@"periodLength" ascending:YES];
NSArray *sortedArray = [originalArray sortedArrayUsingDescriptors:@[endCalYearSD, endMonthSD, periodLenSD]];
This way, your originalArray
will be sorted first by endCalYear, each entry with the same endCalYear will be sorted by endMonth, and each entry with same endCalYear and endMonth will then be sorted by periodLendth.
You have APIs that use an array of sortDescriptors for most of the APIs that propose sorting (including CoreData and such) so the principle is the same all the time.
If you really need to stick with only one NSSortDescriptor
(and your sorting algorithm isn't flexible enough to use a block-based comparator or an array of NSSortDescriptors
), you can simply provide a property to your custom object that compute some value on which you can base your sorting algorithm.
For example add such method to your custom class:
-(NSUInteger)sortingIndex {
return endCalYear*10000 + endCalMonth*100 + periodLength;
}
Then sort on this key/property. This is not really very clean to read and a very pretty design pattern, but the better way would be to alter your sorting algorithm API to allow sorting on multiple keys at once, so…
[EDIT] (to answer your [EDIT] on block-based API)
I don't see why the block-based API sortDescriptorWithKey:ascending:comparator:
won't work for you. You can specify whatever custom NSComparator
block you need there, so this block can tell, given two objects, which one is before the other. The way you determine which one is before which one is up to you, you can compare only endCalYear
, or endCalYear
and endMonth
, etc. so there is no limitation here about sorting using multiple keys.
NSArray
, which results from aNSFetchedResultsController
request. It would be perfect if the sort could be combined withNSFetchedResultsController
(for instance asNSSortDescriptor
). – Honeyman