我有一本字典:
{
"2014-04-12" = (
{
"can_remove" = 1;
"date_created" = "12-04-2014 04:23:57";
"is_connected" = 0;
name = "J J";
status = gbn;
"user_id" = 94;
}
);
"2014-04-14" = (
{
"can_remove" = 0;
"date_created" = "14-04-2014 02:36:52";
"is_connected" = 0;
name = abc;
"user_id" = 89;
}
);
}
此词典的键代表日期。我该如何按日期对此进行排序?
我试过这个,但它不起作用:
NSArray* keys = [dict allKeys];
NSArray* sortedArray = [keys sortedArrayUsingComparator:^(id a, id b) {
return [a compare:b options:NSNumericSearch];
}];
答案 0 :(得分:2)
使用以下方式根据日期对字典进行排序:
NSMutableArray *dictKeys = [[dict allValues] mutableCopy];
[dictKeys sortUsingComparator: (NSComparator)^(NSDictionary *a, NSDictionary *b)
{
NSString *key1 = [a objectForKey: @"field3"];
NSString *key2 = [b objectForKey: @"field3"];
return [key1 compare: key2];
}
];
NSLog (@"dictKeys - %@",dictKeys);
答案 1 :(得分:1)
试试这段代码:
NSArray *sortedArray = [[myDict allKeys] sortedArrayUsingSelector:@selector(compare:)];
答案 2 :(得分:0)
检查此代码..
// currentDic has all data.
NSArray * tempArray = currentDic.allKeys;
NSDateFormatter * formatter = [[NSDateFormatter alloc] init];
[formatter setDateFormat:@"yyyy-MM-dd"];
NSArray * sortedArray = [tempArray sortedArrayUsingComparator:^NSComparisonResult(NSString * obj1, NSString * obj2) {
NSDate * firstDate = [formatter dateFromString:obj1];
NSDate * secondDate = [formatter dateFromString:obj2];
return [firstDate compare:secondDate];
}];
如果你需要它作为字典,那么
NSMutableDictionary * resultingDic = [NSMutableDictionary dictionary];
[sortedArray enumerateObjectsUsingBlock:^(NSString * obj, NSUInteger idx, BOOL *stop) {
resultingDic[obj] = currentDic[obj];
}];