获取按其相应值排序的NSDictionary键 [英] Getting NSDictionary keys sorted by their respective values

查看:338
本文介绍了获取按其相应值排序的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,
}

$ b b

我想结束数组 [D,A,C,B]

推荐答案

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

BTW,这取自:
https://developer.apple.com/library/mac/#documentation/Cocoa/Conceptual/Collections/Articles/Dictionaries.html

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

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