按 NSDate 作为内键对字典数组进行排序

Sort Array of Dictionaries by NSDate as inner key

我想按日期对以下数组进行排序。我尝试了几种方法但没有用。这里的日期字符串是字典的内键。

数组是这样的

{
    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;
    };
},

我试过这段代码,但没用

#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]];

为什么这不起作用?

您不能使用 NSSortDescriptor 按内键对字典的字典数组进行排序。为什么不直接使用 NSMutableArray 的 sortUsingComparator(_:) 方法来比较字典呢?

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];

看起来您正在使用 ISO 8601,在这种情况下,您可以节省一些计算量,因为它可以按字典顺序排序(对于正年份)。

在这种情况下,您可以使用以下排序描述符

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