【问题标题】:Sorting NSMutableArray that contains NSMutableDictionary by the dictionary key's value按字典键的值对包含 NSMutableDictionary 的 NSMutableArray 进行排序
【发布时间】:2012-11-08 10:17:23
【问题描述】:

我有一个包含 70 个对象的 NSMutableArray,它们是 NSMutableDictionary,在每个字典中我有 2 个值:“距离”和“索引路径”。我想将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;
}

我想使用NSMutableDictionary 中的这个“距离”键值将NSMutableArray 从小数排序到大数。我尝试了一些来自网络和 stackoverflow 的代码,但找不到适合我的东西。

请帮帮我!

谢谢!

【问题讨论】:

    标签: objective-c ios nsmutablearray nsdictionary nssortdescriptor


    【解决方案1】:

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

    【讨论】:

    • 感谢您的回答,但它不起作用,sortedArray 仍然与 branchDistance 相同。
    • @YossiTsafar 请确认距离的存储方式。是使用NSNumber 还是使用NSString?如果是后者,则使用前者,因为这样更容易使用。
    • 请告诉我,如果我想使用“名称”而不是距离对其进行排序?意思是字符而不是数字。我该怎么做?
    • @YossiTsafar 您可以使用大致相同的代码,除了NSString 提供了compare:caseInsensitiveCompare: 方法,这意味着您不需要if (x &lt; y) ... 语句。如果您想要更完整的答案,请提出另一个 SO 问题,我将提供完整的代码片段(此问题不在主题范围内)。
    • 让我自己试试,如果我不成功我会再问一个问题。谢谢。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-06-03
    • 2011-07-08
    • 2012-03-19
    相关资源
    最近更新 更多