Reputation: 11297
I am getting date/time as JSON that I am storing as a series of NSArray objects.
The JSON format is as follows:
"created_at" = "2012-09-21T12:41:26-0500"
How do I sort my array so that the latest items are at the very top.
Thank You
Upvotes: 0
Views: 449
Reputation: 5438
The first thing you need to do is convert the date string into an NSDate
object for every one of the items inside your original array, this is key, as the system knows how to compare dates, but not ISO8601 strings.
There are several ways to do the conversion, in the example bellow I am using a custom category on NSDate, you can use the answer to this question for the conversion: Is there a simple way of converting an ISO8601 timestamp to a formatted NSDate?,
Once you have NSDates
, sorting is extremely easy using an NSSortDescriptor
as shown bellow:
NSArray *originalArray = @[
@{@"created_at" : [NSDate dateFromISO8601String:@"2012-09-21T12:41:26-0500"]},
@{@"created_at" : [NSDate dateFromISO8601String:@"2012-07-21T12:41:26-0500"]},
@{@"created_at" : [NSDate dateFromISO8601String:@"2012-06-21T12:41:26-0500"]},
@{@"created_at" : [NSDate dateFromISO8601String:@"2012-10-21T12:41:26-0500"]}
];
NSSortDescriptor *sortDescriptor =
[[NSSortDescriptor alloc] initWithKey:@"created_at" ascending:NO];
NSArray *sortedArray =
[originalArray sortedArrayUsingDescriptors:@[sortDescriptor]];
The variable sortedArray
contains a sorted version of your original array, and as you can see we pass an array of sort descriptors, this allows you to pass multiple sort descriptors, in case you want to sort basen on the date and another property (e.g. title, name) as a secodnary descriptor.
Upvotes: 1