用于排序的 API 通常能够使用 的数组NSSortDescriptors
,而不仅仅是一个,那么为什么不使用它们呢?
例如,NSArray
有一个名为sortedArrayUsingDescriptors:
(注意复数形式)的方法,它接受一个对象数组NSSortDescriptor
。
所以你可以简单地写这个:
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]];
这样,您originalArray
将首先按 endCalYear 排序,具有相同 endCalYear 的每个条目将按 endMonth 排序,然后每个具有相同 endCalYear 和 endMonth 的条目将按 periodLendth 排序。
对于大多数提议排序的 API(包括 CoreData 等),您有使用 sortDescriptor 数组的 API,因此原则始终相同。
如果您真的只需要坚持一个NSSortDescriptor
(并且您的排序算法不够灵活,无法使用基于块的比较器或数组NSSortDescriptors
),您可以简单地为您的自定义对象提供一个属性,该属性计算一些您可以使用的值基于您的排序算法。
例如,将此类方法添加到您的自定义类中:
-(NSUInteger)sortingIndex {
return endCalYear*10000 + endCalMonth*100 + periodLength;
}
然后按此键/属性排序。这不是很干净的阅读和一个非常漂亮的设计模式,但更好的方法是改变你的排序算法 API 以允许一次对多个键进行排序,所以......</p>
[编辑](回答您关于基于块的 API 的 [编辑])
我不明白为什么基于块的 APIsortDescriptorWithKey:ascending:comparator:
不适合你。你可以在那里指定你需要的任何自定义NSComparator
块,所以这个块可以告诉,给定两个对象,哪个在另一个之前。您确定哪个在哪个之前取决于您的方式,您只能比较endCalYear
, 或endCalYear
和endMonth
等,因此这里对使用多个键进行排序没有限制。