Looping in NSMutableDictionary

How do I scroll all objects in an NSMutableDictionary regardless of keys?

+85
ios objective-c nsmutabledictionary
Oct 12 2018-10-12
source share
6 answers

The standard way would look like this:

for(id key in myDict) { id value = [myDict objectForKey:key]; [value doStuff]; } 
+197
Oct 12 2018-10-12
source share

you can use

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

if your target OS supports blocks.

+26
Aug 02 2018-12-12T00:
source share

You can use [dict allValues] to get the NSArray your values. Keep in mind that it does not guarantee any order between calls.

+21
12 Oct 2018-10-12
source share

You do not need to assign a value to a variable. You can access it directly with myDict[key] .

  for(id key in myDict) { NSLog(@"Key:%@ Value:%@", key, myDict[key]); } 
+3
Aug 26 '16 at 6:50
source share
  • For a simple loop, fast enumeration is slightly faster than a block-based loop
  • It is easier to perform parallel or backward enumeration using block enumeration than with fast enumeration. When cyclized with NSDictionary, you can get the key and value in one hit with the enumerator block, while with fast enumeration you must use the key to retrieve the value in a separate message.

in quick listing

 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 }]; 
+2
Aug 12 '14 at 10:06
source share

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

 NSEnumerator *enumerator = [myDictionary objectEnumerator]; id value; while ((value = [enumerator nextObject])) { /* code that acts on the dictionary's values */ } 
+1
Apr 23 '13 at 13:28
source share



All Articles