对 NSString 的 NSArray 进行排序
有人可以告诉我用于排序 NSMutableArray 的代码吗?我有以下 NSMutableArray: ,
NSMutableArray *arr = [[NSMutableArray alloc] init];
其中包含“2”、“4”、“5”、“1”、“9”等元素,这些元素都是 NSString。
我想按降序对列表进行排序,以便最大值的整数在列表中最高(索引 0)。
我尝试了以下操作:
[arr sortUsingSelector:@selector(compare:)];
但它似乎没有正确排序我的值。
有人可以向我展示正确完成我想要完成的任务的代码吗?谢谢!
Can someone please show me the code for sorting an NSMutableArray? I have the following NSMutableArray:
NSMutableArray *arr = [[NSMutableArray alloc] init];
with elements such as "2", "4", "5", "1", "9", etc which are all NSString.
I'd like to sort the list in descending order so that the largest valued integer is highest in the list (index 0).
I tried the following:
[arr sortUsingSelector:@selector(compare:)];
but it did not seem to sort my values properly.
Can someone show me code for properly doing what I am trying to accomplish? Thanks!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
您应该使用此方法:
在
NSArray
中或:在“就地”排序中
NSMutableArray
比较器应返回以下值之一:
NSOrderedAscending
NSOrderedSame
You should use this method:
in a
NSArray
or:in a "inplace" sorting
NSMutableArray
The comparator should return one of this values:
NSOrderedAscending
NSOrderedDescending
NSOrderedSame
编写自己的字符串比较方法非常简单:
It's pretty simple to write your own comparison method for strings:
如果数组的元素只是带有数字而没有字母的 NSString(即“8”、“25”、“3”等),那么这里有一个实际有效的干净而简短的方法:
完成!无需编写返回
NSComparisonResult
的整个方法,或八行NSSortDescriptor
...If the array's elements are just NSStrings with digits and no letters (i.e. "8", "25", "3", etc.), here's a clean and short way that actually works:
Done! No need to write a whole method that returns
NSComparisonResult
, or eight lines ofNSSortDescriptor
...恕我直言,对此类数组进行排序的最简单方法是
如果您的数组包含浮点值,只需将键更改为 self.floatValue 或 self.doubleValue
IMHO, easiest way to sort such array is
If your array contains float values, just change key to
self.floatValue
orself.doubleValue
最简单的方法是创建一个像这样的比较器方法
The easiest way would be to make a comparator method like this one