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…
I save the result of a Json (after a call to an URL) in a NSMutableDictionary and then I have two different “print”:
- if I try to print the dictionary from console with command “po myDictionary” I have an order (the order of the original json)
- if I create a simple “for statement” and print every elements in myDictionary, I have a different order.
How is it possible? Shouldn’t they have the same order?
Thank to all!
EDIT: 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];
}
After the “for statement” this is what happened:
- if I see all the logs I receive something (for example if myDictionary has the name of the day I have something like “Saturday, Monday, Friday…..”)
- if I insert a breakpoint here and try to print something from console with the command “po myDictionary” I have another order, (“sunday, tuesday, monday, …”)
The question is: why?
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”.
The
po <object>command in gdb prints the output of[<object> description].[NSDictionary description]sorts its output by key. This is documented behavior.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.
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.
The correct encoding is an array of single-key objects such as:
But if you can use sorted keys to define order, that’s appropriate.