zoukankan      html  css  js  c++  java
  • iOS: Sorted Array with Compare

    Question(提问):

    What I want to do seems pretty simple, but I can't find any answers on the web. I have an NSMutableArray of objects, let's say they are 'Person' objects. I want to sort the NSMutableArrayby Person.birthDate which is an NSDate.

    I think it has something to do with this method:

    NSArray*sortedArray =[drinkDetails sortedArrayUsingSelector:@selector(???)];

    In Java I would make my object implement Comparable, or use Collections.sort with an inline custom comparator...how on earth do you do this in Objective-C?

    Anwser(回答):

    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];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];
    }];

    转自:http://stackoverflow.com/a/805589(Stack Overflow) 

  • 相关阅读:
    The best programmers are the quickest to Google
    NetBeans 时事通讯(刊号 # 117 Sep 16, 2010)
    Apache HttpClient 4.0.3 GA 发布
    warning LNK4070的解决办法
    看泡沫
    早秋精神
    NetBeans 时事通讯(刊号 # 117 Sep 16, 2010)
    Maven 3.0 RC1 发布
    关于类的数据成员的访问权限设计的一些思考
    看泡沫
  • 原文地址:https://www.cnblogs.com/ihojin/p/ios-sort-with-compare.html
Copyright © 2011-2022 走看看