Why NSURLConnection delegate methods don't get

2019-05-12 08:46发布

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.

1条回答
叛逆
2楼-- · 2019-05-12 09:37

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?

查看更多
登录 后发表回答