objective-c 按降序对数组(NSArray)进行排序
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1938948/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Sorting array(NSArray) in descending order
提问by Girish Kolari
I have a array of NSString objects which I have to sort by descending.
我有一个 NSString 对象数组,我必须按降序对它们进行排序。
Since I did not find any API to sort the array in descending order I approached by following way.
由于我没有找到任何 API 来按降序对数组进行排序,因此我通过以下方式进行了处理。
I wrote a category for NSString as listed bellow.
我为 NSString 编写了一个类别,如下所示。
- (NSComparisonResult)CompareDescending:(NSString *)aString
{
NSComparisonResult returnResult = NSOrderedSame;
returnResult = [self compare:aString];
if(NSOrderedAscending == returnResult)
returnResult = NSOrderedDescending;
else if(NSOrderedDescending == returnResult)
returnResult = NSOrderedAscending;
return returnResult;
}
Then I sorted the array using the statement
然后我使用语句对数组进行排序
NSArray *sortedArray = [inFileTypes sortedArrayUsingSelector:@selector(CompareDescending:)];
Is this right solution? is there a better solution?
这是正确的解决方案吗?有更好的解决方案吗?
回答by Ciarán Walsh
You can use NSSortDescriptor:
您可以使用 NSSortDescriptor:
NSSortDescriptor* sortDescriptor = [NSSortDescriptor sortDescriptorWithKey:nil ascending:NO selector:@selector(localizedCompare:)];
NSArray* sortedArray = [inFileTypes sortedArrayUsingDescriptors:@[sortDescriptor]];
Here we use localizedCompare:to compare the strings, and pass NOto the ascending: option to sort in descending order.
这里我们使用localizedCompare:比较字符串,并传递NO给升序:选项以降序排序。
回答by Jiri Zachar
or simplify your solution:
或简化您的解决方案:
NSArray *temp = [[NSArray alloc] initWithObjects:@"b", @"c", @"5", @"d", @"85", nil];
NSArray *sortedArray = [temp sortedArrayUsingComparator:
^NSComparisonResult(id obj1, id obj2){
//descending order
return [obj2 compare:obj1];
//ascending order
return [obj1 compare:obj2];
}];
NSLog(@"%@", sortedArray);
回答by ankit yadav
NSSortDescriptor *sortDescriptor;
sortDescriptor = [[NSSortDescriptor alloc] initWithKey:@"length" ascending:NO];
NSArray *sortDescriptors = [NSArray arrayWithObject:sortDescriptor];
[wordsArray sortUsingDescriptors:sortDescriptors];
Using this code we can sort the array in descending order on the basis of length.
使用此代码,我们可以根据长度按降序对数组进行排序。

