zoukankan      html  css  js  c++  java
  • NSArray 排序方法的实现

    Compare method

    Either you implement a compare-method for your object:

    -(NSComparisonResult)compare:(Person*)otherObject {return[self.birthDate compare:otherObject.birthDate];}NSArray*sortedArray;
    sortedArray =[drinkDetails sortedArrayUsingSelector:@selector(compare:)];

    NSSortDescriptor (better)

    or usually even better:

    NSSortDescriptor*sortDescriptor;
    sortDescriptor =[[[NSSortDescriptor alloc] initWithKey:@"birthDate"
                                                  ascending:YES] autorelease];NSArray*sortDescriptors =[NSArray arrayWithObject:sortDescriptor];NSArray*sortedArray;
    sortedArray =[drinkDetails sortedArrayUsingDescriptors:sortDescriptors];

    You can easily sort by multiple keys by adding more than one to the array. Using custom comparator-methods is possible as well. Have a look at the documentation.

    Blocks (shiny!)

    There's also the possibility of sorting with a block since Mac OS X 10.6 and iOS 4:

    NSArray*sortedArray;
    sortedArray =[drinkDetails sortedArrayUsingComparator:^NSComparisonResult(id a, id b){NSDate*first =[(Person*)a birthDate];NSDate*second =[(Person*)b birthDate];return[first compare:second];}];
  • 相关阅读:
    java字符串实现正序和倒序输出
    暑假前挑战赛1—— A,B题解
    深搜
    poj 1200 Crazy Search
    poj 1840 Eqs (hash)
    Choose the best route
    一个人的旅行
    畅通工程续
    最短路基础算法
    完全背包问题
  • 原文地址:https://www.cnblogs.com/neozhu/p/2996369.html
Copyright © 2011-2022 走看看