How can i get Original order of NSDictionary/NSMutableDictionary?

Matrix picture Matrix · Aug 2, 2010 · Viewed 17.9k times · Source

i have created NSMutableDictionary with 10 keys.Now i want to access NSMutableDictionary keys in a same order as it was added to NSMutableDictionary (using SetValue:* forKey:* );

How can i achieve that ?

Answer

Alex Reynolds picture Alex Reynolds · Aug 2, 2010

If you absolutely must use a dictionary container, you have to use a key that is sortable by the order in which you add key-value pairs. Thus, when creating your dictionary, you use a key that is an auto-incrementing integer or similar. You can then sort on the (integer) keys and retrieve the values associated with those keys.

If you do all of that, however, you may as well just use an NSMutableArray and add values to the array directly! It will be much faster and require less code. You just retrieve objects in order:

for (id obj in myArray) { /* do stuff with obj... */ }