I have an array that contains a custom class of mine called 'Game'. Each 'Game' contains an NSDate. I would like to reorder my Array based on the dates so that they are in order from newest to oldest. How could I do that? Also, my class 'Game' contains an NSString. How could I reorder my Array so that the games are alphabetized?
2 Answers
There's a REALLY simple way to do this, and that's with an NSSortDescriptor
:
NSArray *games = ...; //your unsorted array of Game objects
NSSortDescriptor *sortByDateDescending = [NSSortDescriptor sortDescriptorWithKey:@"date" ascending:NO];
NSArray *descriptors = [NSArray arrayWithObject:sortByDateDescending];
NSArray *sortedGames = [games sortedArrayUsingDescriptors:descriptors];
Apple's already written the sorting code. It just needs to know what properties to sort by. That's what an NSSortDescriptor
encapsulates. Once you've got one, simply give it to the array, and the array give you back a sorted version. (Alternatively, if you have an NSMutableArray
, you can sort it in-place using -sortUsingDescriptors:
)

- 242,470
- 58
- 448
- 498
The array must be an NSMutableArray object before you can re-order it, correct me if I am wrong.
In order to sort the array you need to write a custom sort method in the Game class. Something like:
- (NSComparisonResult)compareGameByString:(Game *)otherGame
{ return [[self stringValue] caseInsensitiveCompare:[otherGame stringValue]]; }
Then:
[yourMutableArray sortUsingSelector:@selector(compareGameByString:)];
Comparing dates:
- (NSComparisonResult)compareByDate:(Game *)otherGame
{
if( [otherGame isKindOfClass:[Game class]] )
{
// NSdate has a convenient compare method
return [[self dateValue] compare:[otherGame dateValue]];
}
Also note that in the event of your array containing an object that does not respond to these selectors, thus an object that is not a Game object that you will get an exception, and that your app might break

- 6,989
- 1
- 29
- 52
-
1You can sort a regular array using `-[NSArray sortedArrayUsingSelector:]`. Or you can use an `NSSortDescriptor` and not have to worry about writing the comparison code. – Dave DeLong Apr 25 '11 at 00:31