Reputation: 2610
I'm getting an NSDictionary
trough JSON
. When doing a NSLog
the key order is the following: 40617, 40737, 40946, 41066, 41306. That's the order I want because the values are sorted beforehand. But when looping trough the NSDictionary
I get the following order: 40617, 41066, 40737, 40946, 41306. Is it possible to get it in the order I see when I use NSLog
?
Upvotes: 0
Views: 952
Reputation: 5230
You don't have that option by default. You have to customize.
http://www.cocoawithlove.com/2008/12/ordereddictionary-subclassing-cocoa.html
Upvotes: -1
Reputation: 92394
Dictionaries (maps) are unsorted. There is no guaranteed order when you iterate them. You're only guaranteed to get all entries.
So you need to get the keys, sort them in a way you want, and then get the values for your sorted keys.
For example:
NSArray *keys = [myDictionary allKeys];
NSArray *sortedKeys = [keys sortedArrayUsingSelector:@selector(compare:)];
for (id key in sortedKeys) {
id value = [myDictionary objectForKey:key];
NSLog(@"%@ = %@", key, value);
}
Upvotes: 4
Reputation: 20410
The NSDictionary
is not ordered by definition, so when you add the values, they don't have to be the same order all the time. If you want an ordered collection you should use a NSArray
Upvotes: 2