[英]Sorting an NSArray in reverse order
NSArray* sortedArray = [myArray sortedArrayUsingSelector:@selector(compare:)];
Just wondering how I can sort this array of numbers in descending order?只是想知道如何按降序对这个数字数组进行排序?
Either use the method that allows you to pass a block as a comparator and implement a comparator that reverses the objects (returns NSOrderedAscending for NSOrderedDescending and vice versa)....要么使用允许您将块作为比较器传递的方法,要么实现一个反转对象的比较器(为 NSOrderedDescending 返回 NSOrderedAscending,反之亦然)....
... or: ... 要么:
NSArray *reversed = [[[myArray sortedArrayUsingSelector:@selector(compare:)] reverseObjectEnumerator] allObjects];
Sorry.对不起。 Derped the most important part.
删除了最重要的部分。
Use NSSortDescriptor
使用
NSSortDescriptor
NSSortDescriptor* sortOrder = [NSSortDescriptor sortDescriptorWithKey: @"self" ascending: NO];
NSArray *temp = [myArray sortedArrayUsingDescriptors: [NSArray arrayWithObject: sortOrder]];
I like to use the sortedArrayUsingFunction:
method which gives full control of how the array is sorted.我喜欢使用
sortedArrayUsingFunction:
方法,它可以完全控制数组的排序方式。 Then to reverse the results return the negative value of what you would have returned.然后要反转结果,返回您本应返回的负值。
NSInteger myCompare (id obj1, id obj2, void *context) {
int retval = [obj1 compare:obj2 options:NSNumericSearch];
retval = -retval; // now it's sorted reverse
return retval;
}
...
NSArray *arr = @[@"foo20zz", @"foo7zz", @"foo100zz"];
NSArray *sarr = [arr sortedArrayUsingFunction:myCompare context:NULL];
NSLog(@"sarr is %@", sarr);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.