tzippy
tzippy

Reputation: 6638

Sort NSArray by 'Date' Element of included NSDictionaries

Here's what I have: An NSMutableArray that holds several NSDictionary Objects. Each NSDictionary has a Date String as an Element.

Here's my loop that prints out the Date in each NSDictionary

[dateFormatterIn setDateFormat:@"yyyyMMddHHmmss\n"];
[dateFormatterOut setDateFormat:@"dd.MM.yyyy"];     

for(NSMutableDictionary *thisStory in stories){
        id fromDate = [thisStory objectForKey:@"from_time"];
        id date = [dateFormatterIn dateFromString:fromDate];
        NSLog(@"%@", [dateFormatterOut stringFromDate:date]);
    }

Does anyone have a clue how I can sort my array stories by date? I am quite new to objective C. Thanks in advance!

Upvotes: 0

Views: 2452

Answers (2)

Rajan Twanabashu
Rajan Twanabashu

Reputation: 4726

Let's assume Following data structure : array variable name: collectionArray = [ { date: "01-02-2015 02:01", value: 1, name: "rajan" }, { date: "01-02-2014 02:01", value: 11, name: "rajan1" }, { date: "01-02-2012 02:01", value: 111, name: "rajan2" } ]

Now to sort this array of nsdictionary by date we follow the following steps

`NSDateFormatter *formatter = [[NSDateFormatter alloc] init]; [formatter setDateFormat:@"dd-MM-yyyy HH:mm"];

NSMutableArray *sortedArray = [[collectionArray sortedArrayUsingComparator:^NSComparisonResult(NSDictionary *obj1, NSDictionary *obj2) {

    NSString *d1Str =[obj1 valueForKey:@"date"];
    NSString *d2Str =[obj2 valueForKey:@"date"]

    NSString *d1Timestamp = [NSString stringWithFormat:@"%f", [[formatter dateFromString:d1Str] timeIntervalSince1970]];
    NSString *d2Timestamp = [NSString stringWithFormat:@"%f", [[formatter dateFromString:d2Str] timeIntervalSince1970]];

    return [d2Timestamp compare:d1Timestamp options:NSNumericSearch]; // descending order


}] mutableCopy];`

Upvotes: 0

mmoris
mmoris

Reputation: 10340

Using the your stories array's sortUsingDescriptor method should do the trick:

NSSortDescriptor *sortDescriptor = [[[NSSortDescriptor alloc] initWithKey: @"from_time" ascending: YES] autorelease];
[stories sortUsingDescriptors: [NSArray arrayWithObject: sortDescriptor]];

Upvotes: 4

Related Questions