Objective-C语言使用自定义对象对数组进行排序

示例

比较方法

您可以为您的对象实现比较方法:

- (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 *sortDescriptors = [NSArray arrayWithObject:sortDescriptor];
NSArray *sortedArray = [drinkDetails sortedArrayUsingDescriptors:sortDescriptors];

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

积木

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

性能

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