NSArray 排序方法的实现

时间:2022-05-08
本文章向大家介绍NSArray 排序方法的实现,主要内容包括Compare method、NSSortDescriptor (better)、Blocks (shiny!)、基本概念、基础应用、原理机制和需要注意的事项等,并结合实例形式分析了其使用技巧,希望通过本文能帮助到大家理解应用这部分内容。

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