我们假设我有这个NSDictionary:
NSDictionary *d = @{
@"124":@[@"-40",@"1489365614.248664"],
@"130":@[@"-40",@"1489365604.258358"],
@"134":@[@"-40",@"1489365615.49739"],
@"53":@[@"-40",@"1489365610.502131"],
@"57":@[@"-40",@"1489365609.253352"],
@"73":@[@"-40",@"1489365608.004844"],
@"89":@[@"-44",@"1489365611.750874"],
@"91":@[@"-64",@"1489365606.755874"],
@"93":@[@"-45",@"1489365605.507149"],
@"96":@[@"-45",@"1489365613.000054"]
};
我可以按照这个数组的第一个值对它进行排序:
NSArray *sortedKeys = [d keysSortedByValueUsingComparator: ^(NSArray *obj1, NSArray *obj2) {
return (NSComparisonResult)[obj1[0] compare:obj2[0]];
}];
并将返回此数组:
@[73,134,53,124,130,57,89,96,93,91]
翻译成字典的是这样的:
@{
@"73": @[@"-40",@"1489365608.004844"],
@"134":@[@"-40",@"1489365615.49739"],
@"53": @[@"-40",@"1489365610.502131"],
@"124":@[@"-40",@"1489365614.248664"],
@"130":@[@"-40",@"1489365604.258358"],
@"57": @[@"-40",@"1489365609.253352"],
@"89": @[@"-44",@"1489365611.750874"],
@"96": @[@"-45",@"1489365613.000054"],
@"93": @[@"-45",@"1489365605.507149"],
@"91": @[@"-64",@"1489365606.755874"]
};
现在,正如您可能想象的那样,字典中数组的第二个值是时间戳。如果第一个值相等,我想按这个时间戳排序,这样我就可以先获得最新值。
如果我能够做到这一点,我应该回到这样的阵列:
@[134,124,53,57,73,130,89,96,93,91]
将字典翻译为实际上是这样的:
@{
@"134":@[@"-40",@"1489365615.49739"],
@"124":@[@"-40",@"1489365614.248664"],
@"53": @[@"-40",@"1489365610.502131"],
@"57": @[@"-40",@"1489365609.253352"],
@"73": @[@"-40",@"1489365608.004844"],
@"130":@[@"-40",@"1489365604.258358"],
@"89": @[@"-44",@"1489365611.750874"],
@"96": @[@"-45",@"1489365613.000054"],
@"93": @[@"-45",@"1489365605.507149"],
@"91": @[@"-64",@"1489365606.755874"]
};
希望它有意义并且有人有答案。 感谢
答案 0 :(得分:2)
使用此逻辑:
NSArray *sort = [d keysSortedByValueUsingComparator:^(NSArray *obj1, NSArray *obj2) {
NSComparisonResult result = [obj1[0] compare:obj2[0]];
if (result == NSOrderedSame) {
result = [obj2[1] compare:obj1[1]];
}
return result;
}];
答案 1 :(得分:1)
如果有平局,只需比较第二个值......
NSArray *sortedKeys = [d keysSortedByValueUsingComparator: ^(NSArray *obj1, NSArray *obj2) {
NSComparisonResult result = [obj1[0] compare:obj2[0]];
return (result == NSOrderedSame)? [obj2[1] compare:obj1[1]] : result;
}];