ios 如何对 NSArray 中的数字进行排序?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/11179300/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-30 18:56:03  来源:igfitidea点击:

How to sort numbers in NSArray?

objective-cioscocoa-touchplist

提问by Josh Kahane

I can't piece together how to do this.

我不能拼凑如何做到这一点。

I fetch my array from a plist, this array is full of numbers (as set in the plist). Now al I need to do is sort them so they are descending, but I can't work it out.

我从 plist 中获取我的数组,这个数组充满了数字(在 plist 中设置)。现在我需要做的就是对它们进行排序,使它们降序,但我无法解决。

回答by Alexsander Akers

Try this code?

试试这个代码?

 NSArray *array = /* loaded from file */;
 array = [array sortedArrayUsingSelector: @selector(compare:)];

回答by mttrb

The following will sort the numbers in ascending order and then reverse the result to give the numbers in descending order:

以下将按升序对数字进行排序,然后反转结果以按降序给出数字:

NSArray *sorted = [[[array sortedArrayUsingSelector:@selector(compare:)] reverseObjectEnumerator] allObjects];

This previous question has some other alternatives: Sort an NSArray in Descending Order

上一个问题还有其他一些选择: 按降序对 NSArray 进行排序

回答by Ohmy

Here is one of many methods using comparison block. This code snippet is handy for any array with numbers that you want to sort. For Ascending order:

这是使用比较块的众多方法之一。此代码段对于任何包含要排序的数字的数组都很方便。对于升序:

AscendingArray = [UnsortArray sortedArrayUsingComparator:^NSComparisonResult(id obj1, id obj2) {
    if ([obj1 integerValue] > [obj2 integerValue]) {
      return (NSComparisonResult)NSOrderedDescending;
    }

    if ([obj1 integerValue] < [obj2 integerValue]) {
      return (NSComparisonResult)NSOrderedAscending;
    }
    return (NSComparisonResult)NSOrderedSame;
  }];

For Descending order:

对于降序:

DescendingArray = [UnsortArray sortedArrayUsingComparator:^NSComparisonResult(id obj1, id obj2) {
    if ([obj1 integerValue] > [obj2 integerValue]) {
      return (NSComparisonResult)NSOrderedAscending;
    }

    if ([obj1 integerValue] < [obj2 integerValue]) {
      return (NSComparisonResult)NSOrderedDescending;
    }
    return (NSComparisonResult)NSOrderedSame;
  }];

回答by Duyen Hang Kim

It work for me:

它对我有用:

NSSortDescriptor *sortIdClient = 
[NSSortDescriptor sortDescriptorWithKey:@"campaignValue"
                              ascending:NO
                             comparator: ^(id obj1, id obj2){

    return [obj1 compare:obj2 options:NSNumericSearch];

 }];

NSArray *sortDescriptors = @[sortIdClient];

NSArray *arrTemp = [self.allCampaignsList sortedArrayUsingDescriptors:sortDescriptors];

回答by Jasim

This Will solve the problem:

这将解决问题:

 NSArray *array = /* loaded from file */;
 array = [array sortedArrayUsingSelector: @selector(compare:)];