什么时候使用NSArray的各种排序方法?
该 doco 解释了 NSArray 排序方法是什么,但是有人能够给出关于何时/为什么使用特定方法的要点吗?即在您的代码中什么情况下您会使用方法 XXX 而不是方法 YYY。对于:
- :
- sortedArrayUsingSelector
- 上下文
- sortedArrayUsingComparatorsortedArrayUsingDescriptorssortedArrayUsingFunction
The doco explains what the NSArray sort methods are, but is anyone able to give a bullet point say on when/why you'd use a particular method? i.e. under what circumstances in you code would you use method XXX over method YYY. For:
- sortedArrayUsingComparator
- sortedArrayUsingDescriptors
- sortedArrayUsingFunction:context
- sortedArrayUsingSelector
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
请参阅 集合编程主题:数组排序 了解更多一般信息。如果您正在查看课程参考文档,请务必查看列出的“配套指南”,以获取有关课程如何运作的更实用、更真实的建议。
基本上,
sortedArrayUsingSelector:
和sortedArrayUsingFunction:context:
自 10.0/iOS 2.0 以来就已存在。它们不像后来出现的其他方法那么灵活。如果您有一个相对简单的对象数组,例如
NSNumber
或NSString
,您可以使用[numberssortedArrayUsingSelector:@selector(compare:)] 轻松对对象进行排序。
另一方面,如果您有一个更复杂的模型对象,它具有多个属性,例如
age
、name
、date
、NSSortDescriptor 工作良好。这些是在 OS X 10.3/iOS 2.0 中添加的。允许您执行一些操作,例如首先按
年龄
排序,然后按名称
排序,然后按日期
排序。See Collection Programming Topics: Sorting Arrays for more general information. If you're looking at the class reference documentation, be sure to check out the "Companion guides" that are listed for more practical, real-world advice on how the classes work.
Basically,
sortedArrayUsingSelector:
andsortedArrayUsingFunction:context:
have been around since 10.0/iOS 2.0. They're not as flexible as the other methods which came later.If you have an array of relatively simple objects, like
NSNumber
s orNSString
s, you could use[numbers sortedArrayUsingSelector:@selector(compare:)]
to easily sort the objects.If, on the other hand, you have a more complex model object that has multiple properties, such as
age
,name
,date
,NSSortDescriptor
s work well. Those were added in OS X 10.3/iOS 2.0. The allow you to do something like first sort byage
, then byname
, and then bydate
.