获取 NSDictionary 键按各自的值排序 [英] Getting NSDictionary keys sorted by their respective values

查看:19
本文介绍了获取 NSDictionary 键按各自的值排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个带有整数值的 NSMutableDictionary,我想得到一个键数组,按它们各自的值升序排列.例如,使用这本字典:

I have an NSMutableDictionary with integer values, and I'd like to get an array of the keys, sorted ascending by their respective values. For example, with this dictionary:

mutableDict = {
    "A" = 2,
    "B" = 4,
    "C" = 3,
    "D" = 1,
}

我想以数组 ["D", "A", "C", "B"] 结尾.当然,我真正的字典比四项要大得多.

I'd like to end up with the array ["D", "A", "C", "B"]. My real dictionary is much larger than just four items, of course.

推荐答案

NSDictionary 方法 keysSortedByValueUsingComparator: 应该可以解决问题.

The NSDictionary Method keysSortedByValueUsingComparator: should do the trick.

你只需要一个方法返回一个 NSComparisonResult 来比较对象的值.

You just need a method returning an NSComparisonResult that compares the object's values.

你的字典是

NSMutableDictionary * myDict;

你的数组是

NSArray *myArray;

myArray = [myDict keysSortedByValueUsingComparator: ^(id obj1, id obj2) {

     if ([obj1 integerValue] > [obj2 integerValue]) {

          return (NSComparisonResult)NSOrderedDescending;
     }
     if ([obj1 integerValue] < [obj2 integerValue]) {

          return (NSComparisonResult)NSOrderedAscending;
     }

     return (NSComparisonResult)NSOrderedSame;
}];

只需使用 NSNumber 对象而不是数字常量.

Just use NSNumber objects instead of numeric constants.

顺便说一句,这是取自:https://developer.apple.com/library/content/documentation/Cocoa/Conceptual/Collections/Articles/Dictionaries.html

BTW, this is taken from: https://developer.apple.com/library/content/documentation/Cocoa/Conceptual/Collections/Articles/Dictionaries.html

这篇关于获取 NSDictionary 键按各自的值排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆