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) 

  • 相关阅读:
    Redis从入门到精通:初级篇(转)
    Spring配置中的"classpath:"与"classpath*:"的区别研究(转)
    maven常用命令
    JUC-线程池调度-ScheduledThreadPool
    JUC-线程池
    JUC-线程八锁
    JUC-ReadWriteLock
    JUC-Condition和Lock实践-线程按序交替执行
    Linux 查看.so中导出函数
    nginx配置反向代理
  • 原文地址:https://www.cnblogs.com/ihojin/p/ios-sort-with-compare.html
Copyright © 2011-2022 走看看