按NSDate排序字典数组作为内部键

时间:2015-07-26 03:30:25

标签: ios objective-c iphone nsarray nssortdescriptor

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

数组就像这样

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

为什么这不起作用?

2 个答案:

答案 0 :(得分:1)

您无法使用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];

答案 1 :(得分:0)

看起来你正在使用Create Group API,在这种情况下你可以节省一些计算,因为它可以按字典顺序排序(正数年)。

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

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