oc中数组的排序方法归纳

1.通过数组NSArray的方法sortedArrayUsingComparator进行排序,该方法通过代码块方式简单易行:

- (NSArray*)arraySortedByName

{

    NSMutableArray* InfosForSort = [NSMutableArrayarrayWithArray:oldArray];

    

    NSArray *newArray = [InfosForSort sortedArrayUsingComparator:^NSComparisonResult(id obj1, id obj2) {

    //修改以下内容选择指定的数据作为排序的参考

    IssueInfo *info1 = (IssueInfo*)obj1;

    IssueInfo *info2 = (IssueInfo*)obj2;

    NSString *name1 = info1.name;

    NSString *name2 = info2.name;

        

    NSComparisonResult result = [name1 compare:name2];

    return result == NSOrderedAscending// 降序

    }];

    return newArray;

}

 

2.通过NSArray的方法,该方法通过复写compare或者自定义比较函数来实现排序:

NSArray *resultArray = [array sortedArrayUsingSelector:@selector(compare:)]; 

  1. - (NSComparisonResult)compare: (NSDictionary *)otherDictionary  
  2. {  
  3.     NSDictionary *tempDictionary = oldDictionary;  
  4.       
  5.     NSNumber *number1 = [[tempDictionary allKeys] objectAtIndex:0];  
  6.     NSNumber *number2 = [[otherDictionary allKeys] objectAtIndex:0];  
  7.       
  8.     NSComparisonResult result = [number1 compare:number2];  
  9.       
  10.     return result == NSOrderedDescending; // 升序  
  11. //    return result == NSOrderedAscending;  // 降序  

暂时以上两种方法基本解决所有数组排序场景,以后遇到新的好用的方法再更新。

原文地址:https://www.cnblogs.com/ranger-cc/p/3519687.html