Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sort NSArray of date strings or objects

I have an NSArray that contains date strings (i.e. NSString) like this: "Thu, 21 May 09 19:10:09 -0700"

I need to sort the NSArray by date. I thought about converting the date string to an NSDate object first, but got stuck there on how to sort by the NSDate object.

Thanks.

like image 748
postalservice14 Avatar asked Jul 15 '09 17:07

postalservice14


People also ask

Is NSArray ordered?

An object representing a static ordered collection, for use instead of an Array constant in cases that require reference semantics.

What is NSArray Objective-C?

The NSArray class contains a number of methods specifically designed to ease the creation and manipulation of arrays within Objective-C programs. Unlike some object oriented programming languages (C# being one example), the objects contained in an array do not all have to be of the same type.


2 Answers

If I have an NSMutableArray of objects with a field "beginDate" of type NSDate I am using an NSSortDescriptor as below:

NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] initWithKey:@"beginDate" ascending:TRUE]; [myMutableArray sortUsingDescriptors:[NSArray arrayWithObject:sortDescriptor]]; [sortDescriptor release]; 
like image 82
vinzenzweber Avatar answered Sep 20 '22 05:09

vinzenzweber


Store the dates as NSDate objects in an NS(Mutable)Array, then use -[NSArray sortedArrayUsingSelector: or -[NSMutableArray sortUsingSelector:] and pass @selector(compare:) as the parameter. The -[NSDate compare:] method will order dates in ascending order for you. This is simpler than creating an NSSortDescriptor, and much simpler than writing your own comparison function. (NSDate objects know how to compare themselves to each other at least as efficiently as we could hope to accomplish with custom code.)

like image 45
Quinn Taylor Avatar answered Sep 23 '22 05:09

Quinn Taylor