for each loop in Objective-C for accessing NSMutable dictionary
Objective CNsdictionaryEnumerationNsmutabledictionaryKey ValueObjective C Problem Overview
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?
Objective C Solutions
Solution 1 - Objective C
for (NSString* key in xyz) {
id value = xyz[key];
// do stuff
}
This works for every class that conforms to the NSFastEnumeration protocol (available on 10.5+ and iOS), though NSDictionary
is one of the few collections which lets you enumerate keys instead of values. I suggest you read about fast enumeration in the Collections Programming Topic.
Oh, I should add however that you should NEVER modify a collection while enumerating through it.
Solution 2 - Objective C
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);
}];
Solution 3 - Objective C
If you need to mutate the dictionary while enumerating:
for (NSString* key in xyz.allKeys) {
[xyz setValue:[NSNumber numberWithBool:YES] forKey:key];
}
Solution 4 - Objective C
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.
Solution 5 - Objective C
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.
Solution 6 - Objective C
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.
Solution 7 - Objective C
You can use -[NSDictionary allKeys]
to access all the keys and loop through it.