【问题标题】:How to order a NSarray with a dictionary by its values [duplicate]如何通过字典的值对 NSarray 进行排序[重复]
【发布时间】:2013-07-23 04:02:51
【问题描述】:

我有以下NSArray,其中有一个NSDictionary,我需要对它们进行排序,以便更高的字典值位于顶部。

我进行了研究,但找不到对我的 NSDictionary 进行排序的谓词。我怎样才能实现我的目标?

 NSArray* result = @[@{ @"chest":[NSString stringWithFormat:@"%i",[chestR count]]},
                      @{@"back":[NSString stringWithFormat:@"%i",[backR count]]},
                      @{@"triceps":[NSString stringWithFormat:@"%i",[tricepR count]]},
                      @{@"biceps":[NSString stringWithFormat:@"%i",[bicepR count]]},
                      @{@"arms-other":[NSString stringWithFormat:@"%i",[armsR count]]},
                      @{@"legs":[NSString stringWithFormat:@"%i",[legsR count]]},
                      @{@"shoulders":[NSString stringWithFormat:@"%i",[shouldersR count]]},
                      @{@"abs":[NSString stringWithFormat:@"%i",[absR count]]},
                      @{@"cardio":[NSString stringWithFormat:@"%i",[cardioR count]]},
                      @{@"fitness":[NSString stringWithFormat:@"%i",[fitnessR count]]}
                        ];

编辑和解决方案

这就是我解决问题的方法

NSArray* result = @[@{ @"chest":@"5"},
                        @{@"back":@"3"},
                        @{@"triceps":@"4"},
                        @{@"biceps":@"9"},
                        @{@"arms-other":@"1"},
                        @{@"legs":@"0"},
                        @{@"shoulders":@"2"},
                        @{@"abs":@"3"},
                        @{@"cardio":@"8"},
                        @{@"fitness":@"9"}
                        ];

    NSArray *sorted = [result sortedArrayUsingComparator:^(id obj1, id obj2){

        NSArray *s1k = [obj1 allKeys];
        NSInteger s1 = [obj1[[s1k objectAtIndex:0]] intValue];
        NSArray *s2k = [obj2 allKeys];
        NSInteger s2 = [obj2[[s2k objectAtIndex:0]] intValue];

        if ( s1 > s2) {
            return (NSComparisonResult)NSOrderedAscending;
        } else if (s1 < s2) {
            return (NSComparisonResult)NSOrderedDescending;
        }

        return (NSComparisonResult)NSOrderedSame;
    }];

【问题讨论】:

标签: ios objective-c cocoa-touch nsarray nsdictionary


【解决方案1】:

字典没有按定义排序。

您可以将其转换为数组。 NSDictionary 实例方法 -allValues 可能适合这样做。

然后,您可以使用自定义排序描述符对新数组进行排序,以确保它完全按照您想要的方式排序。

【讨论】:

  • 能否请您提供一些关于如何进行排序的示例?
  • 是的,我可以。然而,这里接近午夜,我可能不是处于最佳状态。 :-) 你会在这个问题的答案中找到一个很好的例子。 stackoverflow.com/questions/805547/… 当我拥有自定义排序描述符的契约时,我使用了相同的问题和答案(当时只是没有字典方面)。
  • 您是否需要稍后(排序后)将排序结果放入某个字典中,还是您的问题真的只关注对恰好在字典中的值进行排序?
  • 我需要字典中的结果具有相同的键和值匹配。只需按照字典的值在数组中排序即可。
  • 嗯...你不能。如前所述,您可以将值复制到数组中,然后对其进行排序。你可以建立一个字典,在其中使用值作为键,这一次,键作为值。有几种方法可以在 dict 中切换键和值。但最终无法对这样的字典进行排序。好吧,您可以实现自己的枚举器,但这只会增加额外的复杂性(但可能会节省内存),这会考虑您的排序标准。但坦率地说,一方面是排序的数组,另一方面是具有还原键和值的字典应该满足您的目的。
猜你喜欢
  • 2015-07-15
  • 2012-03-19
  • 2022-01-19
  • 2013-03-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多