Magnus
Magnus

Reputation: 11

Sort array with string dates Objective C

I have an NSMutableArray of Strings. The Strings in the array, are converted from dates to Strings and I need to sort them and show them in a tableview.

I need:

June 24, 2011 June 26, 2011 July 1, 2011

And so on.

I know questions similar to this have been asked, but I didn´t get it to work. So I would really appreciate if someone could help me!

Upvotes: 1

Views: 1234

Answers (3)

Jhaliya - Praveen Sharma
Jhaliya - Praveen Sharma

Reputation: 31722

Your NSMuatbleArray must have the NSDate object.

First you need to sort the array using -[NSMutableArray sortUsingSelector:] and need to pass @selector(compare:).

The compare: function of NSDate will do the job for you and sort the array in ascending order ..

After following the above you just need to call reloadData function of UITableView.

Upvotes: 0

Dan F
Dan F

Reputation: 17732

Easy way to do this is to create a function of the form

NSInteger funcName(id left, id right, void* extra);

you can then use NSMutableArray's sortUsingFunction:context: passing your comparison function in. Jeremy is correct in stating that dates are easier to sort, they have built in comparison functions:

– isEqualToDate:
– earlierDate:
– laterDate:
– compare:

See NSMutableArray for sorting information and NSDate for its comparison methods

Upvotes: 0

Jeremy W. Sherman
Jeremy W. Sherman

Reputation: 36143

Sort them while they're still dates, keep them as a sorted list of dates, and only format them as text as needed for display (i.e., during -tableView:cellForIndexPath:).

Alternatively, the ISO 8601 date formats (an example formatted date would be 20110603T1345.123-4) mostly sort lexicographically the same as they would as dates. Times in different time zones or that cross a summer time shift can invalidate this property, though, so leaving dates as dates would still be your best bet.

Upvotes: 4

Related Questions