简体   繁体   中英

Why NSURLConnection delegate methods don't get called, when using the global dispatch queue?

When I do the following:

dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, NULL), ^{
  create NSURLRequest;
  create NSURLConnectionDelegate;
  create NSURLConnection;
  start NSURLConnection;
});

The delegate's methods never get called. But when I do

dispatch_async(dispatch_get_main_queue(), ^{
  create NSURLRequest;
  create NSURLConnectionDelegate;
  create NSURLConnection;
  start NSURLConnection;
});

They do get called. Why?

UPD

http://developer.apple.com/library/ios/#qa/qa1712/_index.html

Now I do create NSURLConnection; start NSURLConnection; on the main thread.

In the first case, that queue will be drained by some worker thread which mostly likely won't have a runloop running.

In the second case, the queue is drained by your application's main thread, which will have a runloop running. So the delegate methods get scheduled on that runloop.

Hopefully Apple will offer a queue and block based API for this soon. Meanwhile, you might think about ASIHTTPRequest , which allows you to submit blocks to an NSOperationQueue when a connection is finished (or when it fails).

Or you can explicitly configure the NSURLConnection to use the main thread's runloop (or some other specific runloop you know will be around long enough). See -[NSURLConnection – scheduleInRunLoop:forMode:]

Hope that helps?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM