Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

enumerateKeysAndObjectsUsingBlock: can I be sure it is called on the same thread?

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.

like image 470
sumofighter666 Avatar asked Oct 09 '13 22:10

sumofighter666


1 Answers

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.

like image 119
Rob Avatar answered Oct 13 '22 22:10

Rob