How to sort numbers in NSArray?

前端 未结 5 863
深忆病人
深忆病人 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;
      }];
    

提交回复
热议问题