关于日期的字典排序

时间:2013-04-28 15:43:39

标签: ios sorting ios6

Plz指导我如何对这本词典进行排序

dict=
{
"april 2012"=[1,2 ,3 ,4],
"march 2013"=[3,4,6,7],
"may 2013"=[6,7,8,3],
"june 2013"=[6,6,7,8,3],

}

如何根据从新到旧的日期进行排序。

1 个答案:

答案 0 :(得分:1)

运行此代码

NSMutableDictionary *dict = [NSMutableDictionary dictionary];
[dict setObject:@[@6,@6,@7,@8, @3] forKey:@"june 2013"];
[dict setObject:@[@1,@2,@3,@4] forKey:@"april 2012"];
[dict setObject:@[@6,@7,@8,@3] forKey:@"may 2013"];
[dict setObject:@[@3,@4,@6,@7] forKey:@"march 2013"];

NSDateFormatter *dateFormatter = [NSDateFormatter new];
dateFormatter.dateFormat = @"MMMM yyyy";
NSArray *keys = [dict allKeys];
NSArray *sortedKeys = [keys sortedArrayUsingComparator:^NSComparisonResult(id obj1, id obj2) {
    NSDate *date1 = [dateFormatter dateFromString:obj1];
    NSDate *date2 = [dateFormatter dateFromString:obj2];

    return [date1 compare:date2];
}];

NSLog(@"%@", sortedKeys);

我得到了

2013-04-28 18:02:10.322 Test[746:19d03] (
    "april 2012",
    "march 2013",
    "may 2013",
    "june 2013"
)

希望它有所帮助。

修改

要以反向顺序获取数组,请将此返回替换为:

    NSComparisonResult result = [date1 compare:date2];
    if (result == NSOrderedDescending) {
        return NSOrderedAscending;
    } else if (result == NSOrderedAscending) {
        return NSOrderedDescending;
    } else {
        return NSOrderedSame;
    }

或者你可以反转数组的顺序(How can I reverse a NSArray in Objective-C?)或只是按逆序迭代