smartsanja
smartsanja

Reputation: 4540

Sort Array of Dictionaries by NSDate as inner key

I want to sort the following array by dates. I tried several methods but didn't work. Here the date string is an inner key of the dictionary.

Array is like this

{
    message =         {
        "created_at" = "2015-07-23T07:18:42.315Z";
        "created_at_time_ago" = 3ds;
        direction = sent;
    };
},
    {
    message =         {
        "created_at" = "2015-07-21T02:58:23.461Z";
        "created_at_time_ago" = 5ds;
        direction = sent;
    };
},
    {
    message =         {
        "created_at" = "2015-07-19T13:32:22.111Z";
        "created_at_time_ago" = 7ds;
        direction = sent;
    };
},

I tries this code, but didn't work

#define KLongDateFormat @"yyyy-MM-dd'T'HH:mm:ss.SSSZZZZ"


NSDateFormatter *fmtDate = [[NSDateFormatter alloc] init];
[fmtDate setDateFormat:KLongDateFormat];
NSComparator compareDates = ^(id string1, id string2)
{
    NSDate *date1 = [fmtDate dateFromString:string1];
    NSDate *date2 = [fmtDate dateFromString:string2];

    return [date1 compare:date2];
};
NSSortDescriptor * sortDesc1 = [[NSSortDescriptor alloc] initWithKey:@"created_at" ascending:NO comparator:compareDates];
[arrSavedFeeds sortUsingDescriptors:@[sortDesc1]];

Why isn't this working?

Upvotes: 0

Views: 222

Answers (2)

Paul.s
Paul.s

Reputation: 38728

That looks like you are using the ISO 8601 in which case you can save yourself some computation as it can be sorted lexicographically (for positive years).

In which case you can use the following sort descriptor

[NSSortDescriptor sortDescriptorWithKey:@"message.created_at" ascending:NO]

Upvotes: 0

Ozgur Vatansever
Ozgur Vatansever

Reputation: 52133

You can't sort an array of dictionary of dictionary by inner key using NSSortDescriptor. Why don't you just use sortUsingComparator(_:) method of NSMutableArray and compare dictionaries instead?

NSComparator compareDates = ^(id dict1, id dict2)
{
    NSDate *date1 = [fmtDate dateFromString:[[dict1 valueForKey:@"message"] valueForKey:@"created"]];
    NSDate *date2 = [fmtDate dateFromString:[[dict2 valueForKey:@"message"] valueForKey:@"created"]];

    return [date1 compare:date2];
};

[arrSavedFeeds sortUsingComparator:compareDates];

Upvotes: 1

Related Questions