objective-c - 按字典键的值对包含NSMutableDictionary的NSMutableArray进行排序

标签 objective-c ios nsmutablearray nsdictionary nssortdescriptor

我有一个包含70个对象的NSMutableArray,它们是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尝试了一些代码,但是找不到适合我的东西。

请帮我!

谢谢!

最佳答案

我假设使用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];
}];

关于objective-c - 按字典键的值对包含NSMutableDictionary的NSMutableArray进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13286997/

相关文章:

objective-c - 我可以使 NSInteger 成为方法的可选参数吗?

ios - 来自字符串的子字符串特定整数

ios - 如何观察NSMutableArray中单个元素的变化?

ios - 核心图中的两个图可以同时起作用

ios - 核心数据保存数组和字典 - 最佳实践

objective-c - 您可以使用 NSSortDescriptor 按非空值排序吗?

objective-c - 追加 NSMutableArray

ios - 未在不同线程上调用委托(delegate)

iPhone 崩溃日志 - 是什么原因?

ios - prepareForSegue 不会在 Swift 4 中传递数据