【问题标题】:how can I sort NSMutableDictionary with keys value?如何使用键值对 NSMutableDictionary 进行排序?
【发布时间】:2011-11-14 08:23:59
【问题描述】:

我有一个带有字符串键的NSMutableDictionary,每个键都有自己的数组。我想用键值按字母顺序重新排序字典。我该怎么做?

【问题讨论】:

  • 我有未排序的带有键值的 NSMutableDictionary,我想用键值按字母顺序重新排序相同的 NSMutableDictionary。 NSMutableDictionary 有可能吗?

标签: iphone objective-c nsmutabledictionary


【解决方案1】:

字典未按定义排序。

为了以特定顺序遍历键,您可以对包含字典键的数组进行排序。

NSArray *keys = [theDictionary allKeys];
NSArray *sortedKeys = [keys sortedArrayUsingSelector:@selector(compareMethod:)];

还有其他几种sorted... 方法,例如使用NSComparator 进行排序。看看here

【讨论】:

    【解决方案2】:

    用这个

    NSArray *myKeys = [Dict allKeys];
    NSArray *sortedKeys = [myKeys sortedArrayUsingSelector:@selector(caseInsensitiveCompare:)];
    NSMutableArray *sortedValues = [[[NSMutableArray alloc] init] autorelease];
    
    for(id key in sortedKeys) {
        id object = [Dict objectForKey:key];
        [sortedValues addObject:object];
    }
    

    【讨论】:

    • 我使用此代码检索已排序的字典,但仍然未排序 `code NSMutableDictionary *dicProjectListSorted = [NSMutableDictionary dictionary]; NSArray *sortedKeys = [keys sortedArrayUsingSelector:@selector(localizedCaseInsensitiveCompare:)]; NSMutableArray *sortedValues = [[[NSMutableArray alloc] init] autorelease]; for(sortedKeys 中的 id 键) { id 对象 = [dicProjectList objectForKey:key]; [排序值添加对象:对象]; [dicProjectListSorted setObject:sortedValues forKey:key]; }
    • 从这段代码中你得到短键值,然后通过键值你得到你的数据
    • sortedKeys 排序后正确,但是当我尝试在循环中重新创建字典 (dicProjectListSorted) 时,我得到它未排序??
    【解决方案3】:
    NSDictionary *yourDictionary;
    NSArray *sortedKeys = [yourDictionary.allKeys sortedArrayUsingDescriptors:@[[NSSortDescriptor sortDescriptorWithKey:@"self" ascending:YES]]];
    NSArray *sortedValues = [yourDictionary objectsForKeys:sortedKeys notFoundMarker:@""];
    

    【讨论】:

    • 一个有价值的补充是 - 字典(无论是可变的还是不可变的)维护其键的哈希表,因此 - 永远不能真正“排序” - 因此你必须通过另一个集合对象(这里是 NSArray) 是有序的(维护集合中项目的顺序)。
    猜你喜欢
    • 2015-06-03
    • 2012-06-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-06-01
    • 1970-01-01
    相关资源
    最近更新 更多