【问题标题】:How to sort an NSMutableArray containing numbers as strings, in descending order如何按降序对包含数字作为字符串的 NSMutableArray 进行排序
【发布时间】:2014-08-16 19:20:53
【问题描述】:

我正在对一个包含数字字符串的 NSMutableArray 进行排序,以降序。我的数组格式如下:

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

我正在寻找按降序对其进行排序。预期的结果是:

{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:)];

再次输出错误(如下):

{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 发生了什么?我哪里错了吗?有适合我的解决方案吗?请帮我找出问题所在。

【问题讨论】:

    标签: objective-c xcode sorting numbers nsmutablearray


    【解决方案1】:

    试试这个。这可能会有所帮助:

    NSMutableArray *myArray = ....... Your mutable array
    
    NSArray *sorted_Array = [myArray sortedArrayUsingDescriptors:
                                @[[NSSortDescriptor sortDescriptorWithKey:@"intValue"
                                                                ascending:NO]]];
    

    继续编码............ :)

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-08-11
      • 2017-01-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多