-2

I have generated an Array of strings, each is a date from a NSDictionary (parsed from a plist file), the issue is that when creating the Array the NSDictionary has the years in a random order.

my code:

NSString *path = [[NSBundle mainBundle] pathForResource:_country ofType:@"plist"];
    NSDictionary *dict = [[NSDictionary alloc] initWithContentsOfFile:path];

    tableData = [[NSMutableArray alloc] init];

    for (id key in dict) {
        for (NSString *date in [dict objectForKey:key]){
            NSString *baseString = @"";
            baseString = [baseString stringByAppendingFormat:@"%@ %@", date, key];
            [tableData addObject:baseString];
        }
    }

So the above outputs strings like: December 05 2014

What I need is to find a way to then order this array so that the oldest date is first.

DevWithZachary
  • 3,545
  • 11
  • 49
  • 101
  • possible duplicate of [Sort NSArray of date strings or objects](http://stackoverflow.com/questions/1132806/sort-nsarray-of-date-strings-or-objects) – Larme Mar 26 '15 at 15:50
  • Why do you have an array of string dates instead of an array of `NSDate` objects? The latter makes things a lot easier. – rmaddy Mar 26 '15 at 16:12

1 Answers1

-1

The NSArray class has a -sortedArrayUsingComparator: method that you can use to sort it. See the reference here.

You need to provide a suitable comparator as a block, according to the date format you are using. Probably using NSScanner or NSDateFormatter...

NSArray *sortedArray = [tableData sortedArrayUsingComparator: ^(NSString *str1, NSString *str2) {
    if (/* str1 goes before str2 */) {
        return NSOrderedDescending;
    }
    else if (/* str1 goes after str2 */) {
        return NSOrderedAscending;
    }
    else {
        return NSOrderedSame;
    }
}];
Marcos Crispino
  • 8,018
  • 5
  • 41
  • 59