如何按降序对包含数字作为字符串的NSMutableArray进行排序 [英] How to sort an NSMutableArray containing numbers as strings, in descending order

查看:106
本文介绍了如何按降序对包含数字作为字符串的NSMutableArray进行排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在按降序对包含数字作为字符串的 NSMutableArray 进行排序.我的数组格式如下:

I was sorting an NSMutableArray containing numbers as strings, in descending order. My array is in the same form as below:

{273,0,0,0,0,0,48,48,59,254}

我正在寻找按降序排序.预期结果是:

I was looking for sorting it in descending order. That is expected result is:

{273,254,59,48,48,0,0,0,0,0}

我尝试过:

[[[myArray sortedArrayUsingSelector:@selector(compare:)] reverseObjectEnumerator] 
                                                                      allObjects];

结果很奇怪.是:

{59,48,48,273,254,0,0,0,0,0} -- zeros are not getting sorted, and not proper sort

然后我尝试:

[myArray sortedArrayUsingSelector: @selector(compare:)];

输出错误(如下所示):

Again wrong output (as below):

{0,0,0,0,0,254,273,48,48,59} -- zeros came first !!! and 273 in wrong position!!!

我也尝试过:

NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] 
                                       initWithKey:@"length" ascending:YES];
NSArray *sortDescriptors = [NSArray arrayWithObject:sortDescriptor];
[myArray sortUsingDescriptors:sortDescriptors];

再次...结果如下:

{0,0,0,0,0,48,48,59,273,254} -- 273 in wrong position

我完全感到困惑.我需要检查那些零吗?那那273是怎么回事?我在哪里错了?有什么适合我的解决方案吗?请帮助我找出问题所在.

I am totally confused. Do I need to check for those zeros? then whats happening with that 273? Am I wrong anywhere? Is there is any proper solution for me? Please help me finding out the issue.

推荐答案

尝试一下.这可能会帮助:

Try this. This may help:

NSMutableArray *myArray = ....... Your mutable array

NSArray *sorted_Array = [myArray sortedArrayUsingDescriptors:
                            @[[NSSortDescriptor sortDescriptorWithKey:@"intValue"
                                                            ascending:NO]]];

保持编码............:)

Keep Coding............ :)

这篇关于如何按降序对包含数字作为字符串的NSMutableArray进行排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆