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?
You have to create sortDescriptor and then you can sort the nsmutablearray by using sortDescriptor like below.
I did this in iOS 4 using a block. Had to cast the elements of my array from id to my class type. In this case it was a class called Score with a property called points.
Also you need to decide what to do if the elements of your array are not the right type, for this example I just returned
NSOrderedSame
, however in my code I though an exception.PS: This is sorting in descending order.
Sort Array In Swift
For
Swifty
Person below is a very clean technique to achieve above goal for globally. Lets have an example custom class ofUser
which have some attributes.Now we have an array which we need to sort on the basis of
createdDate
either ascending and/or descending. So lets add a function for date comparison.Now lets have an
extension
ofArray
forUser
. In simple words lets add some methods only for those Array's which only haveUser
objects in it.Usage for Ascending Order
Usage for Descending Order
Usage for Same Order
See the
NSMutableArray
methodsortUsingFunction:context:
You will need to set up a compare function which takes two objects (of type
Person
, since you are comparing twoPerson
objects) and a context parameter.The two objects are just instances of
Person
. The third object is a string, e.g. @"birthDate".This function returns an
NSComparisonResult
: It returnsNSOrderedAscending
ifPersonA.birthDate
<PersonB.birthDate
. It will returnNSOrderedDescending
ifPersonA.birthDate
>PersonB.birthDate
. Finally, it will returnNSOrderedSame
ifPersonA.birthDate
==PersonB.birthDate
.This is rough pseudocode; you will need to flesh out what it means for one date to be "less", "more" or "equal" to another date (such as comparing seconds-since-epoch etc.):
If you want something more compact, you can use ternary operators:
Inlining could perhaps speed this up a little, if you do this a lot.
Starting in iOS 4 you can also use blocks for sorting.
For this particular example I'm assuming that the objects in your array have a 'position' method, which returns an
NSInteger
.Note: the "sorted" array will be autoreleased.
You can use the following generic method for your purpose. It should solve your issue.