使用全局调度队列时,为什么不调用NSURLConnection委托方法? [英] Why NSURLConnection delegate methods don't get called, when using the global dispatch queue?

查看:61
本文介绍了使用全局调度队列时,为什么不调用NSURLConnection委托方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我执行以下操作时:

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

现在我知道了 创建NSURLConnection; 启动NSURLConnection; 在主线程上.

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

推荐答案

在第一种情况下,该队列将被某些工作线程耗尽,而该工作线程很可能不会运行runloop.

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

在第二种情况下,队列被应用程序的主线程耗尽,该主线程将运行runloop.这样,委托方法就在该运行循环上进行了调度.

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.

希望苹果不久将为此提供基于队列和块的API.同时,您可能会考虑 ASIHTTPRequest ,它允许您在连接完成后向NSOperationQueue提交块(或失败时).

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).

或者您可以显式配置NSURLConnection以使用主线程的运行循环(或其他一些您知道足够长的运行循环).请参阅-[NSURLConnection – scheduleInRunLoop:forMode:]

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:]

希望有帮助吗?

这篇关于使用全局调度队列时,为什么不调用NSURLConnection委托方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆