本文介绍了按降序排序数组(NSArray)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个NSString对象数组,我必须通过降序排序。
I have a array of NSString objects which I have to sort by descending.
由于我没有找到任何API按降序排序数组我靠近
Since I did not find any API to sort the array in descending order I approached by following way.
我为下面列出的NSString写了一个类别。
I wrote a category for NSString as listed bellow.
- (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?
推荐答案
您可以使用NSSortDescriptor:
You can use NSSortDescriptor:
NSSortDescriptor* sortDescriptor = [NSSortDescriptor sortDescriptorWithKey:nil ascending:NO selector:@selector(localizedCompare:)];
NSArray* sortedArray = [inFileTypes sortedArrayUsingDescriptors:[NSArray arrayWithObject:sortDescriptor]];
这里我们使用 localizedCompare:
字符串,并将 NO
传递到ascending:选项以按降序排序。
Here we use localizedCompare:
to compare the strings, and pass NO
to the ascending: option to sort in descending order.
这篇关于按降序排序数组(NSArray)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!