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通过单击标题行来对其进行排序。
热门推荐
10 对患者生日祝福语简短
11 结婚祝福语简短装备
12 周岁祝福语学生文案简短
13 订婚领证祝福语简短精辟
14 导师获奖祝福语大全简短
15 新婚购房祝福语简短精辟
16 牛年祝福语简短的爱人
17 送芒果的祝福语简短
18 送给学长毕业祝福语简短