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

问题描述 投票:9回答:5

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

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

objective-c ios cocoa-touch plist
5个回答
39
投票

试试这个代码?

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

13
投票

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

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

之前的问题还有其他一些选择:Sort an NSArray in Descending Order


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;
  }];

对于降序:

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;
  }];

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];

0
投票

这将解决问题:

 NSArray *array = /* loaded from file */;
 array = [array sortedArrayUsingSelector: @selector(compare:)];
© www.soinside.com 2019 - 2024. All rights reserved.