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
- sortedArrayUsing开发者_StackOverflowSelector
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:
and sortedArrayUsingFunction: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 or NSString
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 by age
, then by name
, and then by date
.
精彩评论