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) 

  • 相关阅读:
    XML语法
    C/C++对MySQL操作
    HDU 3966 Aragorn's Story
    SPOJ 375 Query on a tree
    SPOJ 913 Query on a tree II
    SPOJ 6779 Can you answer these queries VII
    URAL 1471 Tree
    SPOJ 2798 Query on a tree again!
    POJ 3237 Tree
    SPOJ 4487 Can you answer these queries VI
  • 原文地址:https://www.cnblogs.com/ihojin/p/ios-sort-with-compare.html
Copyright © 2011-2022 走看看