我想做的事情看起来很简单,但我在网上找不到任何答案。我有一个NSMutableArray
对象,假设它们是“Person”对象。我想排序NSMutableArray
通过 Person.birthDate 这是一个NSDate
.
我认为这与这个方法有关:
NSArray *sortedArray = [drinkDetails sortedArrayUsingSelector:@selector(???)];
在 Java 中,我会让我的对象实现 Comparable,或者使用 Collections.sort 和内联自定义比较器...在 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 *sortedArray = [drinkDetails sortedArrayUsingDescriptors:@[sortDescriptor]];
通过向数组添加多个键,您可以轻松地按多个键进行排序。也可以使用自定义比较器方法。看一下文档 https://developer.apple.com/library/mac/documentation/Cocoa/Reference/Foundation/Classes/NSSortDescriptor_Class/Reference/Reference.html.
块(闪亮!)
从 Mac OS X 10.6 和 iOS 4 开始,还可以使用块进行排序:
NSArray *sortedArray;
sortedArray = [drinkDetails sortedArrayUsingComparator:^NSComparisonResult(Person *a, Person *b) {
return [a.birthDate compare:b.birthDate];
}];
表现
The -compare:
一般来说,基于块的方法比使用NSSortDescriptor
因为后者依赖于 KVC。主要优点NSSortDescriptor
方法的优点是它提供了一种使用数据而不是代码来定义排序顺序的方法,这使得例如可以轻松地设置好以便用户可以对NSTableView
单击标题行。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)