博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
iOS: Sorted Array with Compare
阅读量:6121 次
发布时间:2019-06-21

本文共 1653 字,大约阅读时间需要 5 分钟。

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 .

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://vimka.baihongyu.com/

你可能感兴趣的文章
解决窗体切换闪屏
查看>>
9g10在nandflash扇区的分配地址
查看>>
myeclipse 手动安装 lombok
查看>>
Linux 精确获取指定目录对应的块的剩余空间
查看>>
10分钟教会你Apache Shiro
查看>>
ruby设计模式之合成模式1————基本的合成模式
查看>>
GridView中实现可收缩的面板
查看>>
Linux下用freetds执行SqlServer的sql语句和存储过程
查看>>
JavaScript类的实现实例
查看>>
C#序列化与反序列化
查看>>
javascript世界时间
查看>>
vs启动错误
查看>>
如何使用JPA注解标注一对多的关系
查看>>
送给毕业生的一个学习建议
查看>>
【OpenCV学习】图像通道的GRB分割混合
查看>>
一个对Entity Framework数据层的封装
查看>>
收集winform 多线程教程
查看>>
带关闭的漂浮广告
查看>>
SAP HANA存储过程结果视图调用
查看>>
Android使用SAX解析XML(5)
查看>>