zoukankan      html  css  js  c++  java
  • 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;  // 降序  

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

  • 相关阅读:
    python库--pandas--Series.str--字符串处理
    前端--jstree--异步加载数据
    python库--flask--创建嵌套蓝图
    Git--生成公钥和私钥并添加gitlab访问权限
    es查询--请求body
    python生成时间序列(date_range)
    golang使用组合完成伪继承
    golang interface类型的动态绑定
    ruby环境安装草稿
    openfire
  • 原文地址:https://www.cnblogs.com/ranger-cc/p/3519687.html
Copyright © 2011-2022 走看看