I need to traverse all key/values pairs of a dictionary and do something with both fields. I am wondering what is more efficient, the traditional 'foreach key' approach or the blocks approach using enumerateKeysAndObjectsUsingBlock:.
Here you have an example:
Traditional approach (before blocks)
for (NSString* key in [self.dictionary allKeys] ) {
[self processKey:key value: [self.dictionary objectForKey:value ]];
}
Blocks approach.
[self.dictionary enumerateKeysAndObjectsUsingBlock:^(id key, id obj, BOOL *stop){
[self processKey:key value:obj];
}];
My gut feeling is that traversing the key/value pairs using the block is faster, but I am not sure since I don't know how dictionaries and the particular block method is implemented.
Any thoughts?
Thanks in advance!
An object representing a static collection of key-value pairs, for use instead of a Dictionary constant in cases that require reference semantics.
Main Difference is:NSMutableDictionary is derived from NSDictionary, it has all the methods of NSDictionary. NSMutableDictionary is mutable( can be modified) but NSDictionary is immutable (can not be modified).
Use -mutableCopy . NSDictionary *d; NSMutableDictionary *m = [d mutableCopy]; Note that -mutableCopy returns id ( Any in Swift) so you will want to assign / cast to the right type. It creates a shallow copy of the original dictionary.
You can simply say: myDictionary[myWord] = nextValue; Similarly, to get a value, you can use myDictionary[key] to get the value (or nil). The simplified form mentioned above, usually solves problems OCLint (metric static code analysis).
They would be basically the same -- they are both synchronous traversals. However, the following would allow for concurrent traversal, which would be faster:
[self.dictionary enumerateKeysAndObjectsWithOptions:NSEnumerationConcurrent
usingBlock:^(id key, id object, BOOL *stop) {
}];
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With