小编典典

如何对包含自定义对象的 NSMutableArray 进行排序?

all

我想做的事情似乎很简单,但我在网上找不到任何答案。我有一个NSMutableArray对象,假设它们是“人”对象。我想NSMutableArray
Person.birthDate 排序,这是一个NSDate.

我认为这与这种方法有关:

NSArray *sortedArray = [drinkDetails sortedArrayUsingSelector:@selector(???)];

在 Java 中,我会让我的对象实现 Comparable,或者将 Collections.sort 与内联自定义比较器一起使用……你到底是如何在
Objective-C 中做到这一点的?


阅读 92

收藏
2022-02-25

共1个答案

小编典典

比较方法

要么为你的对象实现一个比较方法:

- (NSComparisonResult)compare:(Person *)otherObject {
    return [self.birthDate compare:otherObject.birthDate];
}

NSArray *sortedArray = [drinkDetails sortedArrayUsingSelector:@selector(compare:)];

NSSortDescriptor(更好)

或者通常更好:

NSSortDescriptor *sortDescriptor;
sortDescriptor = [[NSSortDescriptor alloc] initWithKey:@"birthDate"
                                           ascending:YES];
NSArray *sortedArray = [drinkDetails sortedArrayUsingDescriptors:@[sortDescriptor]];

您可以通过向数组添加多个键轻松地按多个键排序。也可以使用自定义比较器方法。看看文档

块(闪亮!)

自 Mac OS X 10.6 和 iOS 4 起,也可以使用块进行排序:

NSArray *sortedArray;
sortedArray = [drinkDetails sortedArrayUsingComparator:^NSComparisonResult(Person *a, Person *b) {
    return [a.birthDate compare:b.birthDate];
}];

表现

一般来说,基于-compare:块的方法比使用NSSortDescriptor后者依赖于 KVC
的方法要快得多。该NSSortDescriptor方法的主要优点是它提供了一种使用数据而不是代码定义排序顺序的方法,这使得设置变得容易,例如,用户可以NSTableView通过单击标题行进行排序。

2022-02-25