Accessing objects in NSMutableDictionary by index

Objective CIphoneCocoa TouchXcode

Objective C Problem Overview


To display key/values from an NSMutableDictionary sequentially (in a tableview), I need to access them by index. If access by index could give the key at that index, I could than get the value. Is there a way to do that or a different technique?

Objective C Solutions


Solution 1 - Objective C

You can get an NSArray containing the keys of the object using the allKeys method. You can then look into that by index. Note that the order in which the keys appear in the array is unknown. Example:

NSMutableDictionary *dict;

/* Create the dictionary. */

NSArray *keys = [dict allKeys];
id aKey = [keys objectAtIndex:0];
id anObject = [dict objectForKey:aKey];

EDIT: Actually, if I understand what you're trying to do what you want is easily done using fast enumeration, for example:

NSMutableDictionary *dict;

/* Put stuff in dictionary. */

for (id key in dict) {
    id anObject = [dict objectForKey:key];
    /* Do something with anObject. */
}

EDIT: Fixed typo pointed out by Marco.

Solution 2 - Objective C

you can get an array of all the keys with the allKeys method of the dictionary; and then you can access the array by index. however, a dictionary by itself does not have an inherent ordering, so the ordering of the keys you get before and after a change to the dictionary can be completely different

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
Question4thSpaceView Question on Stackoverflow
Solution 1 - Objective CBennoView Answer on Stackoverflow
Solution 2 - Objective CnewacctView Answer on Stackoverflow