looping through an NSMutableDictionary

Objective CIosNsmutabledictionary

Objective C Problem Overview


How do I loop through all objects in a NSMutableDictionary regardless of the keys?

Objective C Solutions


Solution 1 - Objective C

A standard way would look like this

for(id key in myDict) {
    id value = [myDict objectForKey:key];
    [value doStuff];
}

Solution 2 - Objective C

you can use

[myDict enumerateKeysAndObjectsUsingBlock: ^(id key, id obj, BOOL *stop) {
    // do something with key and obj
}];

if your target OS supports blocks.

Solution 3 - Objective C

You can use [dict allValues] to get an NSArray of your values. Be aware that it doesn't guarantee any order between calls.

Solution 4 - Objective C

  1. For simple loop, fast enumeration is a bit faster than block-based loop
  2. It's easier to do concurrent or reverse enumeration with block-based enumeration than with fast enumeration When looping with NSDictionary you can get key and value in one hit with a block-based enumerator, whereas with fast enumeration you have to use the key to retrieve the value in a separate message send

in fast enumeration

for(id key in myDictionary) {
   id value = [myDictionary objectForKey:key];
  // do something with key and obj
}

in Blocks :

[myDictionary enumerateKeysAndObjectsUsingBlock:^(id key, id obj, BOOL *stop) {

   // do something with key and obj
  }];

Solution 5 - Objective C

You don't need to assign value to a variable. You can access it directly with myDict[key].

    for(id key in myDict) {
        NSLog(@"Key:%@ Value:%@", key, myDict[key]);
    }

Solution 6 - Objective C

Another way is to use the Dicts Enumerator. Here is some sample code from Apple:

NSEnumerator *enumerator = [myDictionary objectEnumerator];
id value;

while ((value = [enumerator nextObject])) {
    /* code that acts on the dictionary’s values */
}

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
QuestionRupertView Question on Stackoverflow
Solution 1 - Objective CHenrik P. HesselView Answer on Stackoverflow
Solution 2 - Objective CAndrey ZverevView Answer on Stackoverflow
Solution 3 - Objective Cjv42View Answer on Stackoverflow
Solution 4 - Objective Cuser3540599View Answer on Stackoverflow
Solution 5 - Objective CAlexanderView Answer on Stackoverflow
Solution 6 - Objective CHendrikView Answer on Stackoverflow