objective-c - 根据另一个距离数组对对象的 nsmutablearray 进行排序

标签 objective-c

我有两个 nsmutablearrays,一个是距离数组,另一个是包含与这些距离相关联的图像的数组。我需要按升序对距离数组进行排序,然后根据它对图像数组进行排序。我试图用距离数组作为键来制作这两个数组的字典,但是当距离值相同时,在排序的图像数组中返回相同的图像。谁能帮我解决这个问题。 代码如下:

 // Put the two arrays into a dictionary as keys and values
    NSDictionary *dictionary = [NSDictionary dictionaryWithObjects:_locationImages forKeys:_distances];
    // Sort the first array
    NSArray *sortedFirstArray = [[dictionary allKeys] sortedArrayUsingComparator:^NSComparisonResult(id obj1, id obj2) {
        if ([obj1 floatValue] > [obj2 floatValue])
            return NSOrderedDescending;
        else if ([obj1 floatValue] < [obj2 floatValue])
            return NSOrderedAscending;
        return NSOrderedSame;
    }];
    // Sort the second array based on the sorted first array
    NSArray *sortedSecondArray = [dictionary objectsForKeys:sortedFirstArray notFoundMarker:[NSNull null]];           

最佳答案

你不需要距离作为关键。只要有一系列字典。不知何故,这也让排序变得更容易。

NSMutableArray *dataArray = [NSMutableArray array];
for (int i=0; i<distanceArray.count; i++) {
    [dataArray addObject:@{
       @"distance" : distanceArray[i],
       @"image"    : imageArray[i]
    }];
}
NSArray *sorted = [dataArray sortedArrayUsingDescriptors:@[
                   [NSSortDescriptor sortDescriptorWithKey:@"distance"
                                                 ascending:YES]]];

关于objective-c - 根据另一个距离数组对对象的 nsmutablearray 进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14592764/

相关文章:

iOS:不存在的指针正在崩溃应用程序

ios - 获取 UIWebView 的选定文本

objective-c - 当 ARC 将 weak 属性设置为 nil 时,kvo 会发生吗?

iphone - 无法显示带有文本字段的 UIAlertView

iphone - UITabbarController + UINavigationController,使用 UIToolbar 代替标签栏的详细 View

objective-c - 在 Mac OS 编程中,默认值是什么?非原子的还是原子的?

iphone - 如何通过parentviewcontroller将数据从一个 View 传递到另一个 View

ios - 从可变数组访问数据

objective-c - 没有 init 的 Objective C 构造函数

objective-c - 将 NSArray 内容转换为可变参数(使用 ARC)以与 NSString initWithFormat 一起使用