NSMutableDictionary,来自控制台和代码的不同打印 [英] NSMutableDictionary, different print from console and code

查看:180
本文介绍了NSMutableDictionary,来自控制台和代码的不同打印的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对NSMutableDictionary有一些疑问。我读到它们只是一个hashmap的包装器,所以不鼓励它们用于有序列表。

I have some questione about NSMutableDictionary. I read that they are only a wrapper around an hashmap, so their use for ordered list is discouraged.

但是我必须使用它,所以问题就开始了......

But I have to use it, so the problems began...

我在NSMutableDictionary中保存了Json的结果(在调用URL之后),然后我有两个不同的print:

I save the result of a Json (after a call to an URL) in a NSMutableDictionary and then I have two different "print":


  • 如果我尝试使用命令po myDictionary从控制台打印字典我有一个订单(原始json的顺序)

  • 如果我创建一个简单的for语句并打印myDictionary中的每个元素,我会有不同的顺序。

如何有可能吗?他们不应该有相同的订单吗?

How is it possible? Shouldn't they have the same order?

感谢大家!

编辑:这是代码的一个小例子:

this is a little example of the code:

NSMutableDictionary *myDictionary = [--{RECEIVED FROM ANOTHER CALL}--];
NSMutableDictionary *tmp = [NSMutableDictionary dictionaryWithCapacity:[myDictionary count]];

for(NSString *key in myDictionary) {
    NSLog(@"%@", key);

    NSObject *object = [[NSObject alloc] init]

    /* some operation in the code with object */

    [tmp setObject:object forKey:key];
}

在for statement之后发生了这样的事情:

After the "for statement" this is what happened:


  • 如果我看到我收到的所有日志(例如,如果myDictionary的名称是周六,周一,周五...... ..)

  • 如果我在这里插入断点并尝试使用命令po myDictionary从控制台打印一些东西我还有另一个订单,(星期日,星期二,星期一,... 。)

问题是:为什么?

编辑2:我知道存在一个拥有OrderedDictionary的系统,但这不是问题:我想理解为什么我有两个不同的打印,一个来自for statement而另一个来自po command。

EDIT 2: I know that there exists a system to have an "OrderedDictionary", but it isn't the question: I want to understand why I have two different print, one from the "for statement" and the other from "po command".

推荐答案

po< object> gdb中的命令打印的输出[< object>描述 [NSDictionary description] 按键对其输出进行排序。这是记录的行为

The po <object> command in gdb prints the output of [<object> description]. [NSDictionary description] sorts its output by key. This is documented behavior.

如果您的JSON按键排序(听起来像是这样),那么您可以再次按键排序以确保订单可靠。

If your JSON is sorted by key (which it sounds like it is), then you can just sort by key again to ensure a reliable order.

请注意,如果您的JSON使用对象(键/值对的集合)来表示有序数据,则它违反了 JSON规范

Note that if your JSON is using an object (a collection of key/value pairs) to represent ordered data, it is in violation of the JSON spec.


一个对象是一个零个或多个名称/值对的无序集合,其中名称是字符串,值是字符串,数字,布尔值,空值,对象或数组。

An object is an unordered collection of zero or more name/value pairs, where a name is a string and a value is a string, number, boolean, null, object, or array.

正确的编码是单键对象数组,例如:

The correct encoding is an array of single-key objects such as:

[ { "firstKey": "value" }, { "secondKey": "value" } ]

但如果可以的话使用排序键来定义顺序,这是合适的。

But if you can use sorted keys to define order, that's appropriate.

这篇关于NSMutableDictionary,来自控制台和代码的不同打印的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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