0

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

Strong Like Bull
  • 11,155
  • 36
  • 98
  • 169
  • Does this help? [NSArray sorting](http://www.cocoanetics.com/2009/03/nsarray-sorting-using-selectors/) – Anshu Sep 23 '12 at 06:55

1 Answers1

1

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.

Community
  • 1
  • 1
Zebs
  • 5,378
  • 2
  • 35
  • 49