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?
I have created a small library of category methods, called Linq to ObjectiveC, that makes this sort of thing more easy. Using the sort method with a key selector, you can sort by
birthDate
as follows:I tried all, but this worked for me. In a class I have another class named "
crimeScene
", and want to sort by a property of "crimeScene
".This works like a charm:
Your
Person
objects need to implement a method, saycompare:
which takes anotherPerson
object, and returnNSComparisonResult
according to the relationship between the 2 objects.Then you would call
sortedArrayUsingSelector:
with@selector(compare:)
and it should be done.There are other ways, but as far as I know there is no Cocoa-equiv of the
Comparable
interface. UsingsortedArrayUsingSelector:
is probably the most painless way to do it.For
NSMutableArray
, use thesortUsingSelector
method. It sorts it-place, without creating a new instance.