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;  // 降序  

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

  • 相关阅读:
    代理模式和装饰模式的理解
    Mysql常用命令
    java动态代理(JDK和cglib)
    MyEclipse中SVN使用步骤
    ActionContext和ServletActionContext小结
    java和unicode
    Win7下telnet使用
    MyEclipse8.5安装SVN插件
    linux常用命令(基础)
    选择TreeView控件的树状数据节点的JS方法
  • 原文地址:https://www.cnblogs.com/ranger-cc/p/3519687.html
Copyright © 2011-2022 走看看