更改 - [NSArray sortedArrayUsingComparator:]的排序顺序 [英] Changing the sort order of -[NSArray sortedArrayUsingComparator:]
问题描述
我需要从另一个 NSArray
生成 NSNumber
的排序数组。我想使用 sortedArrayUsingComparator:
方法。我在Apple文档中找到了这个例子:
I need to generate a sorted array of NSNumber
s from another NSArray
. I want to use the sortedArrayUsingComparator:
method. I found this example in the Apple documentation:
NSArray *sortedArray = [array sortedArrayUsingComparator: ^(id obj1, id obj2) {
if ([obj1 integerValue] > [obj2 integerValue]) {
return (NSComparisonResult)NSOrderedDescending;
}
if ([obj1 integerValue] < [obj2 integerValue]) {
return (NSComparisonResult)NSOrderedAscending;
}
return (NSComparisonResult)NSOrderedSame;
}];
这里我只是提供一个块中的比较器,这是很好。排序本身 - 对我隐藏的位,使用这个块 - 似乎是升序。
Here I am just providing the comparator in a block, which is fine. The sort itself -- the bit that's hidden from me, which uses this block -- appears to be ascending.
我想知道如果我可以请求这个块外部的不同排序顺序,或者我只需要翻转<
和>
的(或 NSOrderedXXX
)?
I'd like to know if I can request a different sort order external to this block, or do I just need to flip the <
and >
's (or NSOrderedXXX
's) around?
推荐答案
如果你想下降排序,只需翻转比较(或翻转 NSComparisonResult
s)。没有必要通过一个上升:
参数,当你可以直接控制在块中膨胀API。
If you want to sort descending, then just flip the comparisons (or flip the NSComparisonResult
s). There's no need to bloat the API by having an ascending:
parameter when you can control that in the block directly.
这篇关于更改 - [NSArray sortedArrayUsingComparator:]的排序顺序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!