【问题标题】:Dictionary Key Sorting [duplicate]字典键排序[重复]
【发布时间】:2013-09-14 00:46:08
【问题描述】:

您好,我有一本由我设置并正在访问的字典 代码如下。

NSMutableDictionary* filteredDictionary = [NSMutableDictionary dictionary];
    [filteredDictionary setObject:@"xcode" forKey:@"1"];
    [filteredDictionary setObject:@"ios" forKey:@"3"];
    [filteredDictionary setObject:@"ipad" forKey:@"2"];
    [filteredDictionary setObject:@"iphone" forKey:@"5"];
    [filteredDictionary setObject:@"simulator" forKey:@"4"];

   NSLog(@"%@",filteredDictionary);

当前输出:

{

1 = xcode;
2 = ipad;
3 = ios;
4 = simulator;
5 = iphone;    
}
but i want 
{
1 = xcode;
3 = ios;
2 = ipad;
5 = iphone;
4 = simulator;
}

我想要字典,因为我在其中设置对象

我不想让字典按照它排序

请帮忙

提前致谢.....

【问题讨论】:

标签: ios objective-c nsmutabledictionary


【解决方案1】:

NSDictionary 不记得您添加键的顺序。你必须自己做。我建议使用NSMutableOrderedSet

NSMutableDictionary* filteredDictionary = [NSMutableDictionary dictionary];
NSMutableOrderedSet* keyOrder = [[NSMutableOrderedSet alloc] init];

[filteredDictionary setObject:@"xcode" forKey:@"1"];
[keyOrder addObject: @"1"];
[filteredDictionary setObject:@"ios" forKey:@"3"];
[keyOrder addObject: @"3"];

// etc

显然这是一个令人头疼的问题,所以为自己创建一个新的集合类

@implementation MyMutableOrderedDictionary
{
     NSMutableDictionary* filteredDictionary = [NSMutableDictionary dictionary];
     NSMutableOrderedSet* keyOrder = [[NSMutableOrderedSet alloc] init];

}

-(void) setObject: (id) object forKey: (id <NSCopying>) key
{
    [filteredDictionary setObject: object forKey: key];
    [keyOrder addObject: key]; 
} 
-(NSOrderedSet*) keys
{
    return keyOrder;
}

// Some other methods

@end

您可以通过在内部迭代 keyOrder 或在外部迭代 keys 属性来实现一些枚举方法。

请注意,我没有将 NSMutableDictionary 子类化,因为它是一个类集群,这可能会让人头疼。

【讨论】:

    【解决方案2】:

    NSDictonary 并不意味着对对象进行排序,考虑元素的顺序绝对不重要。 NSditonary 是一组键值对,预计使用相应的键访问值,因此index 的概念在其中没有用处。 如果你想在索引上玩,你应该使用 NSArray。

    【讨论】:

      【解决方案3】:

      NSDictionary 不保证您访问时的顺序。如果你想保持元素的顺序,你必须使用 NSArray。

      像 OrderedDictionary (http://www.cocoawithlove.com/2008/12/ordereddictionary-subclassing-cocoa.html) 这样的想法很少,但最好将正确的对象用于正确的目的。

      【讨论】:

        【解决方案4】:

        您不能就地对键进行排序,因为字典是哈希表。

        您可以将键/值对作为数组获取,并在显示之前对数组进行排序:

        https://stackoverflow.com/a/4558777/15721

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2015-04-07
          • 2016-11-06
          • 2011-12-06
          • 1970-01-01
          • 1970-01-01
          • 2019-05-14
          • 1970-01-01
          相关资源
          最近更新 更多