Lately I am using enumerateKeysAndObjectsUsingBlock:
and today I have hesitated when one of my colleague at work place pointed out that this enumeration method can be called from separate thread and my code may not work as expected. He even suggested I should use fast enumeration. Problem is I really like enumerateKeysAndObjectsUsingBlock:
and dislike fast enumeration due to its nature when it comes to dictionary.
my method looked as following
- (NSArray *)someMethod
{
__block NSMutableArray *myArray = [NSMutableArray array];
[self.myDictionary enumerateKeysAndObjectsUsingBlock:^(id key, id obj, BOOL *stop) {
[myArray addObject:obj];
}
return myArray;
}
Can I be sure that myArray will always return the expected values (assuming self.myDictionary
is not empty) and it will be always called on the same thread as the someMethod?
I am aware there is a method enumerateKeysAndObjectsWithOptions:usingBlock:
and calling it with NSEnumerationConcurrent
option will run enumeration simultaneously on multiple threads.
But I can't find any documentation regarding enumerateKeysAndObjectsUsingBlock
.
The same refers to enumerateObjectsUsingBlock:
used on array.
As you observe, unless you call enumerateKeysAndObjectsWithOptions
with the NSEnumerationConcurrent
option, you can be assured that they won't be performed concurrently. As to whether the non-concurrent rendition of enumerateKeysAndObjects
runs on the same thread or not (though, I'd wager it does), it doesn't really matter if it didn't run on the same queue because this is run synchronously with respect to the thread that you called the enumeration method. Bottom line, your coworker's thread-related concerns are without merit.
I would note, though, that in my anecdotal testing, these enumeration methods are slower than fast enumeration. If speed is of paramount interest (e.g. especially if using huge dictionaries/arrays), then you might want to employ fast enumeration. In most scenarios, though, the difference is not material.
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