adit
adit

Reputation: 33674

sendAsynchronousRequest NSURLConnectionRequest

In the method below, if I do data processing in the completionHandler, is this going to block the main thread or not? In other words is whatever performed in the completionHandler done on the main thread or is it done on the background thread?

+ (void)sendAsynchronousRequest:(NSURLRequest *)request
                          queue:(NSOperationQueue*) queue
              completionHandler:(void (^)(NSURLResponse*, NSData*, NSError*)) handler NS_AVAILABLE(10_7, 5_0);

Upvotes: 0

Views: 943

Answers (2)

Just a coder
Just a coder

Reputation: 16730

It depends on the OS version you are supporting. According to the documentation, the completion handler block is executed on a NSOperationQueue.

+(void)sendAsynchronousRequest:(NSURLRequest *)request
                      queue:(NSOperationQueue*) queue
          completionHandler:(void (^)(NSURLResponse*, NSData*, NSError*)) handler NS_AVAILABLE(10_7, 5_0);

Several lines down into the NSOperationQueue documentation, you will see this quote:

Operation queues usually provide the threads used to run their operations. In OS X v10.6 and later, operation queues use the libdispatch library (also known as Grand Central Dispatch) to initiate the execution of their operations. As a result, operations are always executed on a separate thread, regardless of whether they are designated as concurrent or non-concurrent operations. In OS X v10.5, however, operations are executed on separate threads only if their isConcurrent method returns NO. If that method returns YES, the operation object is expected to create its own thread (or start some asynchronous operation); the queue does not provide a thread for it.

Note: In iOS 4 and later, operation queues use Grand Central Dispatch to execute operations. Prior to iOS 4, they create separate threads for non-concurrent operations and launch concurrent operations from the current thread. For a discussion of the difference between concurrent and non-concurrent operations and how they are executed, see NSOperation Class Reference.

If your app is supporting OSX v10.6 and above, then the completion handler should be executed on a separate thread. In OS X v10.5, you will have to specify it. For iOS it's also using GCD so operations are also executed on separate threads from iOS 4 and upwards. Hope that was clearer than Tommy's response.

Upvotes: 0

Tommy
Tommy

Reputation: 100652

Per the documentation, queue is:

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

So handler will be performed there. Notably no promises are made either way as to where the actual URL connection stuff will be done, so if you want to finish on the main thread you should just specify [NSOperationQueue mainQueue].

Upvotes: 1

Related Questions