请指导我如何对这本字典进行排序
听写= { “2012 年 4 月”=[1,2 ,3 ,4], “2013 年 3 月”=[3,4,6,7], “2013 年 5 月”=[6,7,8,3], “2013 年 6 月”=[6,6,7,8,3], }
如何根据日期从新到旧排序。
运行此代码
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"
)
希望能帮助到你。
编辑
要以相反的顺序获取数组,请将 return 替换为:
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?)或者只是以相反的顺序迭代