0

I've objects of array, in each object i have different type of strings in one string i am getting date from xml parsing, now my task is that to sort whole data according to time wise(like before date then current date then after date). I am having two problems.

  1. How to sort array on this structure like objects of arrays if simple then it'll more easy for me?
  2. Which function should I use to sort date wise?
vikingosegundo
  • 52,040
  • 14
  • 137
  • 178
Aleem
  • 3,173
  • 5
  • 33
  • 71
  • Possible duplicate of this question : [http://stackoverflow.com/questions/1132806/sort-nsarray-of-date-strings-or-objects](http://stackoverflow.com/questions/1132806/sort-nsarray-of-date-strings-or-objects) – Ilanchezhian Nov 28 '11 at 05:20
  • Might be duplicate, but old: no objc-block solution posted there. – vikingosegundo Nov 28 '11 at 06:22

1 Answers1

3

One of several options would be using a comparator block. You didn't provide enough informations, so I made some assumptions:

  • The date string is at the 3rd index of the NSArrays
  • The date string looks like 31-12-2011

Code

NSDateFormatter *dateFormatter = [[[NSDateFormatter alloc] init] autorelease];
[dateFormatter setDateFormat:@"dd-MM-yyyy"];

array = [array sortedArrayUsingComparator: ^(id a, id b) {
    NSArray *array1 = (NSArray *)a;
    NSArray *array2 = (NSArray *)b;
    NSDate *date1 = [dateFormatter dateFromString:[array1 objectAtIndex:2]];
    NSDate *date2 = [dateFormatter dateFromString:[array2 objectAtIndex:2]];

    return [date1 compare:date2]
}

But you should also consider to have an class representing the data.
In that case you would inter ate over the raw dater and create a object for every data set, put it in an NSMutableArray and sort this. similar.

vikingosegundo
  • 52,040
  • 14
  • 137
  • 178
  • WHOA! did you just use a block in there? Wow, that's pretty clever (which is making me think I should try to use more of these clever block tricks)! Excellent answer! – Cashew Oct 10 '12 at 14:24