1

我有一个NSMutableArray有70个对象,它们是NSMutableDictionary,每个字典里面我有2个值:“distance”和“indexPath”。我想从小距离到最大排序NSMutableArray。距离是KM和阵列看起来像这样利用我粘贴在这里的代码之后:使用字典键的值对包含NSMutableDictionary的NSMutableArray进行排序

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以内。我尝试了一些来自web和stackoverflow的代码,但找不到适合我的东西。

请帮帮我!

谢谢!

回答

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]; 
}]; 
+0

谢谢您的回答,但它不工作时,'sortedArray'仍然是一样的branchDistance。 –

+0

@YossiTsafar请确认距离的存储方式。它使用'NSNumber'还是使用'NSString'?如果后者使用前者则更容易使用。 – trojanfoe

+0

现在工作很好,谢谢! –

相关问题