How to sort an NSMutableArray containing numbers as strings, in descending order

本小妞迷上赌 提交于 2019-12-11 07:11:15

问题


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}

I tried:

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

The result was weird. It was:

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

Then I tried:

[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!!!

And I also tried:

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

Again... Result is as below:

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

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.


回答1:


Try this. This may help:

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

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

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



来源:https://stackoverflow.com/questions/25343140/how-to-sort-an-nsmutablearray-containing-numbers-as-strings-in-descending-order

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!