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

老子叫甜甜 提交于 2019-12-07 17:22:11

问题


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:


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?



来源:https://stackoverflow.com/questions/5474845/why-nsurlconnection-delegate-methods-dont-get-called-when-using-the-global-dis

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!