I’ve noticed that the enumerated output of a NSDictionary is not returning the same sequence as the order in which the items were added.
NSMutableArray *arrKeys;
NSMutableArray *arrValues;
NSDictionary *items;
arrKeys = [NSMutableArray arrayWithCapacity:5];
arrValues = [NSMutableArray arrayWithCapacity:5];
[arrKeys addObject:@"A"]; [arrValues addObject:@"First"];
[arrKeys addObject:@"B"]; [arrValues addObject:@"Second"];
[arrKeys addObject:@"C"]; [arrValues addObject:@"Third"];
[arrKeys addObject:@"D"]; [arrValues addObject:@"Fourth"];
[arrKeys addObject:@"E"]; [arrValues addObject:@"Last"];
items = [NSDictionary dictionaryWithObjects:arrValues forKeys:arrKeys];
for (NSString *aKey in items) {
NSLog(@"%@=%@", aKey, [items valueForKey:aKey]);
}
Returns…
A=First
D=Fourth
B=Second
E=Last
C=Third
I appreciate that a Dictionary allows you to randomly access items by key, but is there some rationale for the arbitrary order they are returned while enumerating the collection?
That’s just that, an
NSDictionarydoes not guarantee iteration order. This is consistent with the behavior you’d expect from a typical hash table — optimized for quick lookup, but not for ordered iteration.Why not iterate through
arrKeysthat you already have?