Changing the sort order of -[NSArray sortedArrayUsingComparator:]

风流意气都作罢 提交于 2019-11-30 11:09:28

If you want to sort descending, then just flip the comparisons (or flip the NSComparisonResults). There's no need to bloat the API by having an ascending: parameter when you can control that in the block directly.

From the documentation for -sortedArrayUsingComparator: :

"Returns an array that lists the receiving array’s elements in ascending order, as determined by the comparison method specified by a given NSComparator Block."

So You'd have to resort to using

- (NSArray *)sortedArrayUsingDescriptors:(NSArray *)sortDescriptors

but of course that means rolling your own NSSortDescriptor objects first, which may suit your purposes just fine.

You can flip the operators around.

The "bit that's hidden from you" doesn't care about ascending or descending, as it doesn't know anything about your objects. It's like asking your co-worker if a hockey puck is greater or less than a muskrat. The internal implementation just uses a sorting algorithm (which is probably determined using the size of your array) and uses your block function to compare two objects.

Just change the logic:

NSArray *sortedArray = [array sortedArrayUsingComparator: ^(id obj1, id obj2) {

 if ([obj1 integerValue] > [obj2 integerValue]) {
      return (NSComparisonResult)NSOrderedAscending;
 }

 if ([obj1 integerValue] < [obj2 integerValue]) {
      return (NSComparisonResult)NSOrderedDescending;
 }
 return (NSComparisonResult)NSOrderedSame;
}];

For clarity it might be best to make this a method with a name similar to: decendingSort.

mikebob

As a side note, you are able to get the reversed order of an array using this

[[NSArray reverseObjectEnumerator] allObjects];

Source: https://stackoverflow.com/a/586529/1382210

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!