如何排序包含一个NSMutableArray数字字符串,按降序排列(How to sort an N

2019-10-20 17:42发布

我被排序包含数字作为字符串一个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发生? 我错了地方? 有没有对我任何妥善的解决办法? 请帮我找出这个问题。

Answer 1:

尝试这个。 这可以帮助:

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

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

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



文章来源: How to sort an NSMutableArray containing numbers as strings, in descending order