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.
An object representing a static ordered collection, for use instead of an Array constant in cases that require reference semantics.
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.
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];
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.)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With