How to sort numbers in NSArray?

2020-05-21 05:17发布

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.

5条回答
2楼-- · 2020-05-21 05:23

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];
查看更多
虎瘦雄心在
3楼-- · 2020-05-21 05:24

Try this code?

 NSArray *array = /* loaded from file */;
 array = [array sortedArrayUsingSelector: @selector(compare:)];
查看更多
该账号已被封号
4楼-- · 2020-05-21 05:28

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

查看更多
干净又极端
5楼-- · 2020-05-21 05:35

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;
  }];
查看更多
Rolldiameter
6楼-- · 2020-05-21 05:36

This Will solve the problem:

 NSArray *array = /* loaded from file */;
 array = [array sortedArrayUsingSelector: @selector(compare:)];
查看更多
登录 后发表回答