[objective-c] for each loop in Objective-C for accessing NSMutable dictionary

I am finding some difficulty in accessing mutable dictionary keys and values in Objective-C.

Suppose I have this:

NSMutableDictionary *xyz=[[NSMutableDictionary alloc] init];

I can set keys and values. Now, I just want to access each key and value, but I don't know the number of keys set.

In PHP it is very easy, something as follows:

foreach ($xyz as $key => $value)

How is it possible in Objective-C?

The answer is


Just to not leave out the 10.6+ option for enumerating keys and values using blocks...

[dict enumerateKeysAndObjectsUsingBlock:^(id key, id object, BOOL *stop) {
    NSLog(@"%@ = %@", key, object);
}];

If you want the actions to happen concurrently:

[dict enumerateKeysAndObjectsWithOptions:NSEnumerationConcurrent
                              usingBlock:^(id key, id object, BOOL *stop) {
    NSLog(@"%@ = %@", key, object);
}];

If you need to mutate the dictionary while enumerating:

for (NSString* key in xyz.allKeys) {
    [xyz setValue:[NSNumber numberWithBool:YES] forKey:key];
}

You can use -[NSDictionary allKeys] to access all the keys and loop through it.


I suggest you to read the Enumeration: Traversing a Collection’s Elements part of the Collections Programming Guide for Cocoa. There is a sample code for your need.


Fast enumeration was added in 10.5 and in the iPhone OS, and it's significantly faster, not just syntactic sugar. If you have to target the older runtime (i.e. 10.4 and backwards), you'll have to use the old method of enumerating:

NSDictionary *myDict = ... some keys and values ...
NSEnumerator *keyEnum = [myDict keyEnumerator];
id key;

while ((key = [keyEnum nextObject]))
{
    id value = [myDict objectForKey:key];
    ... do work with "value" ...
}

You don't release the enumerator object, and you can't reset it. If you want to start over, you have to ask for a new enumerator object from the dictionary.


The easiest way to enumerate a dictionary is

for (NSString *key in tDictionary.keyEnumerator) 
{
    //do something here;
}

where tDictionary is the NSDictionary or NSMutableDictionary you want to iterate.


Examples related to objective-c

Adding a UISegmentedControl to UITableView Keep placeholder text in UITextField on input in IOS Accessing AppDelegate from framework? Warp \ bend effect on a UIView? Use NSInteger as array index Detect if the device is iPhone X Linker Command failed with exit code 1 (use -v to see invocation), Xcode 8, Swift 3 ITSAppUsesNonExemptEncryption export compliance while internal testing? How to enable back/left swipe gesture in UINavigationController after setting leftBarButtonItem? Change status bar text color to light in iOS 9 with Objective-C

Examples related to nsdictionary

How to append elements into a dictionary in Swift? Converting NSString to NSDictionary / JSON convert NSDictionary to NSString How do I deserialize a JSON string into an NSDictionary? (For iOS 5+) How to use NSJSONSerialization adding multiple entries to a HashMap at once in one statement How can I convert NSDictionary to NSData and vice versa? How to add to an NSDictionary NSDictionary to NSArray? NSDictionary - Need to check whether dictionary contains key-value pair or not

Examples related to enumeration

How to iterate a loop with index and element in Swift Java Enum Methods - return opposite direction enum What does the "map" method do in Ruby? iterating through Enumeration of hastable keys throws NoSuchElementException error Java getting the Enum name given the Enum Value Search for a string in Enum and return the Enum for each loop in Objective-C for accessing NSMutable dictionary (How) can I count the items in an enum? Collection was modified; enumeration operation may not execute in ArrayList Case objects vs Enumerations in Scala

Examples related to nsmutabledictionary

for each loop in Objective-C for accessing NSMutable dictionary How can we store into an NSDictionary? What is the difference between NSDictionary and NSMutableDictionary?

Examples related to key-value

Iterate through dictionary values? How can I get key's value from dictionary in Swift? How to add a new object (key-value pair) to an array in javascript? How to search if dictionary value contains certain string with Python Python: How to check if keys exists and retrieve value from Dictionary in descending priority How do you create a dictionary in Java? how to prevent adding duplicate keys to a javascript array How to update value of a key in dictionary in c#? How to create dictionary and add key–value pairs dynamically? How to count frequency of characters in a string?