我有一个NSMutableArray
有70个对象,它们是NSMutableDictionary
,在每个字典里面我有2个值:“distance”和“indexPath”。我想将NSMutableArray
从小距离排序到最大距离。使用我粘贴的代码后,距离以KM为单位,数组看起来像这样:
NSSortDescriptor *descriptor = [NSSortDescriptor sortDescriptorWithKey:@"distance" ascending:YES];
[branchDistance sortedArrayUsingDescriptors:[NSArray arrayWithObjects:descriptor,nil]];
这是此方法的结果:
(lldb) po [branchDistance objectAtIndex:0]
(id) $1 = 0x0d6ac240 {
"<NSIndexPath 0xd6cf180> 1 indexes [0]" = indexPath;
"8.078547" = distance;
}
(lldb) po [branchDistance objectAtIndex:1]
(id) $2 = 0x0d6a64a0 {
"<NSIndexPath 0xd6cf3b0> 1 indexes [1]" = indexPath;
"45.044069" = distance;
}
(lldb) po [bran(lldb) po [branchDistance objectAtIndex:2]
(id) $4 = 0x0d6cf550 {
"<NSIndexPath 0xd69b3f0> 1 indexes [2]" = indexPath;
"9.992081" = distance;
}
(lldb) po [branchDistance objectAtIndex:3]
(id) $5 = 0x0d6cf750 {
"283.356727" = distance;
"<NSIndexPath 0xd6cf480> 1 indexes [3]" = indexPath;
}
我希望使用NSMutableArray
内的“距离”键值,将NSMutableDictionary
从小数字排序为大数字。我从网络和stackoverflow尝试了几段代码,但是找不到对我有用的东西。
请帮助我!
谢谢!
答案 0 :(得分:5)
我假设距离值使用NSNumber
对象存储在词典中:
NSArray *sortedArray = [branchDistance sortedArrayUsingComparator:^(id obj1, id obj2) {
NSNumber *distance1 = [(NSDictionary *)obj1 objectForKey:@"distance"];
NSNumber *distance2 = [(NSDictionary *)obj2 objectForKey:@"distance"];
return [distance1 compare:distance2];
}];