Reputation: 2571
Suppose there is an NSDictionary *dict
.
What is the difference between the following?
for (id key in dict) {
NSLog(@"value: %@", dict[key]);
}
for (id key in [dict allKeys]) {
NSLog(@"value: %@", dict[key]);
}
I didn't know that the first version existed, and when I saw it I thought it would be a compile-time error.
Upvotes: 1
Views: 74
Reputation: 2993
The first variant uses NSDictionaries implementation of "fast enumeration" (NSFastEnumeration Protocol), while the second uses the NSArray implementation. I suspect that the first variant would be ever so slightly faster (at least it is a little less typing).
BTW you can also write
for (NSString *key in dict)
{
NSLog(@"value: %@", dict[key]);
}
Note that unlike what a previous poster suggests, this is NOT a guarantee that all keys are NSString objects. It merely is an implicit casting of key
to NSString *
.
Upvotes: 3
Reputation: 104
for (id key in dict) {
NSLog(@"value: %@", dict[key]);
}
here you are not sure wether your key is NSString
or NSNumber
or any NSObject
for (NSString *key in [dict allKeys]) {
NSLog(@"value: %@", dict[key]);
}
whereas in this code snippet you are sure that the keys for the dictionary is NSString
Upvotes: 0