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) 

  • 相关阅读:
    scrapy模拟用户登录
    我为什么选择Vim
    关于72键配列键盘的想法
    vim配图
    解决一些python的问题记录
    ros资料记录,详细阅读
    C语言的历史
    将制定目录家到系统PATH环境变量中
    让vim更加智能化
    如何自定义路径
  • 原文地址:https://www.cnblogs.com/ihojin/p/ios-sort-with-compare.html
Copyright © 2011-2022 走看看