What I want to do seems pretty simple, but I can't find any answers on the web. I have an NSMutableArray
of objects, and let's say they are 'Person' objects. I want to sort the NSMutableArray
by Person.birthDate which is an NSDate
.
I think it has something to do with this method:
NSArray *sortedArray = [drinkDetails sortedArrayUsingSelector:@selector(???)];
In Java I would make my object implement Comparable, or use Collections.sort with an inline custom comparator...how on earth do you do this in Objective-C?
Swift's protocols and functional programming makes that very easy you just have to make your class conform to the Comparable protocol, implement the methods required by the protocol and then use the sorted(by: ) high order function to create a sorted array without need to use mutable arrays by the way.
There is a missing step in Georg Schölly's second answer, but it works fine then.
I've used sortUsingFunction:: in some of my projects:
Compare method
Either you implement a compare-method for your object:
NSSortDescriptor (better)
or usually even better:
You can easily sort by multiple keys by adding more than one to the array. Using custom comparator-methods is possible as well. Have a look at the documentation.
Blocks (shiny!)
There's also the possibility of sorting with a block since Mac OS X 10.6 and iOS 4:
Performance
The
-compare:
and block-based methods will be quite a bit faster, in general, than usingNSSortDescriptor
as the latter relies on KVC. The primary advantage of theNSSortDescriptor
method is that it provides a way to define your sort order using data, rather than code, which makes it easy to e.g. set things up so users can sort anNSTableView
by clicking on the header row.Thanks, it's working fine...