How to sort numbers in NSArray?

2020-05-21 05:00发布

问题:

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.

回答1:

Try this code?

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


回答2:

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



回答3:

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


回答4:

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


回答5:

This Will solve the problem:

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