Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is NSURLConnection sendAsynchronousRequest completion block executed on the main thread?

I am wondering whether the completionHandler block is called on the main thread, when I use NSURLConnection sendAsynchronousRequest. My main concern is whether I need to dispatch UIKit calls on the main thread by myself.

The document for NSURLConnection did not mention this detail, unless I missed it.

I profiled my code, and there was no memory leak, which kind of indicating that the block was executed on the main thread.

Is there any document that gives definite answer?

[NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
    [self.progress stopAnimating];
    if (data != nil) {
        ...
    } else {
        [self showMessageIgnoreAcknowledgement:@"Error" message:@"blah"];
    }
}];
like image 801
Peter Pei Guo Avatar asked Aug 04 '14 03:08

Peter Pei Guo


1 Answers

From the documentation for the NSURLConnection sendAsynchronousRequest:queue:completionHandler: method:

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

Also from the comment about the queue parameter:

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

Since you are passing in the main queue, the completion handler will be on the main thread (the main queue is on the main thread).

like image 132
rmaddy Avatar answered Oct 11 '22 10:10

rmaddy