How to sort numbers in NSArray?

前端 未结 5 851
深忆病人
深忆病人 2021-02-03 11:55

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

相关标签:
5条回答
  • 2021-02-03 12:29

    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;
      }];
    
    0 讨论(0)
  • 2021-02-03 12:35

    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];
    
    0 讨论(0)
  • 2021-02-03 12:37

    Try this code?

     NSArray *array = /* loaded from file */;
     array = [array sortedArrayUsingSelector: @selector(compare:)];
    
    0 讨论(0)
  • 2021-02-03 12:37

    This Will solve the problem:

     NSArray *array = /* loaded from file */;
     array = [array sortedArrayUsingSelector: @selector(compare:)];
    
    0 讨论(0)
  • 2021-02-03 12:38

    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

    0 讨论(0)
提交回复
热议问题