Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is the Objective-C dictionary an ordered container?

as the title, when I insert element to a dictionary in objective-c (in order like: k1, k2, k3), is there any guarantee that when I enumerate it like:

for ( k in dictionary ){
   // output the k - value
}

it would show in the same order?

like image 914
fallhunter Avatar asked Oct 30 '09 04:10

fallhunter


People also ask

Why are dictionaries not ordered?

You don't access sequentially to a dictionary as you would when, for example, iterating a list or array. You access by having a key, then finding whether there's a value for that key on the dictionary and what is it.

What is dictionary Objective C?

Objective-C Dictionary Object classes allow data to be stored and managed in the form of key-value pairs where both the key and the value are objects.

Does NSDictionary retain objects?

An NSDictionary will retain it's objects, and copy it's keys.

How do I add an array to a dictionary in Objective C?

So if you need to add arrays for more than one key you might do this: Given an array of two keys: NSArray *keys = [NSArray arrayWithObjects:@"key0",@"key1", nil]; And a dictionary...


2 Answers

No, NSDictionary does not maintain the insertion order of its keys.

If you need a dictionary that maintains insertion order, I'd suggest using the CHDataStructures framework, which has a CHOrderedDictionary class (it's a descendent of NSMutableDictionary). The documentation for CHOrderedDictionary says:

A dictionary which enumerates keys in the order in which they are inserted.

The following additional operations are provided to take advantage of the ordering:

-firstKey

-lastKey

-keyAtIndex:

-reverseKeyEnumerator

Key-value entries are inserted just as in a normal dictionary, including replacement of values for existing keys, as detailed in -setObject:forKey:. However, an additional structure is used in parallel to track insertion order, and keys are enumerated in that order. If a key to be added does not currently exist in the dictionary, it is added to the end of the list, otherwise the insertion order of the key does not change.

like image 171
Dave DeLong Avatar answered Nov 08 '22 08:11

Dave DeLong


NSDictionary's keys aren't kept in order, but you can get them and sort them, E. G:

for (key in [[myDict allKeys] sortedArrayUsingSelector:@selector(compare:)])
...
like image 32
NSResponder Avatar answered Nov 08 '22 09:11

NSResponder