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

Jos*_*ane 9 cocoa-touch objective-c plist ios

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

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

Ale*_*ers 39

试试这个代码?

 NSArray *array = /* loaded from file */;
 array = [array sortedArrayUsingSelector: @selector(compare:)];
Run Code Online (Sandbox Code Playgroud)

  • `-compare:` 方法是为 `NSNumber` 实例定义的:https://developer.apple.com/library/mac/documentation/Cocoa/Reference/Foundation/Classes/NSNumber_Class/Reference/Reference.html#//apple_ref /occ/instm/NSNumber/比较: (2认同)

mtt*_*trb 14

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

NSArray *sorted = [[[array sortedArrayUsingSelector:@selector(compare:)] reverseObjectEnumerator] allObjects];
Run Code Online (Sandbox Code Playgroud)

此前一个问题还有其他一些选择: 按降序排序NSArray


Ohm*_*hmy 12

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

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;
  }];
Run Code Online (Sandbox Code Playgroud)

对于降序:

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;
  }];
Run Code Online (Sandbox Code Playgroud)


Duy*_*Kim 5

它对我有用:

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];
Run Code Online (Sandbox Code Playgroud)