Search code examples
objective-cmultithreadinggrand-central-dispatchblocksendasynchronousrequest

Are Objective-C blocks always executed in a separate thread?


Are Objective-C blocks always executed in a separate thread?

Specifically, I'm asking about the sendAsynchronousRequest:queue:completionHandler method of the NSURLConnection class. This is the scenario:

Main thread (1st thread) calls the sendAsynchronousRequest method the sendAsynchronousRequest is executed on a 2nd thread, managed by the NSOperationQueue when method is completed and calls commpletionHandler, which thread is it executed on? 2nd thread? yet another 3rd thread? or the 1st thread?

Thanks!


Solution

  • It executes it on whatever operation queue you specify as the queue argument:

    Loads the data for a URL request and executes a handler block on an operation queue when the request completes or fails.

    The queue parameter is documented as:

    The operation queue to which the handler block is dispatched when the request completes or failed.

    So it's really up to the NSOperationQueue exactly how many threads are used. I'd expect pooling behaviour - so while there can be multiple threads, I wouldn't expect a different thread per handler, necessarily.