【问题标题】:NSURLConnectionDelegate methods not called when using NSThread使用 NSThread 时未调用 NSURLConnectionDelegate 方法
【发布时间】:2014-07-29 19:43:07
【问题描述】:

我正在尝试在后台线程中运行下载,以免阻塞 iOS 上的主 UI 线程,我所做的是使用

创建一个新线程
[NSThread detachNewThreadSelector:@selector(startDownload) toTarget:downloadObject withObject:nil];

然后下面的代码在后台线程上运行:

NSURL* urlForCalendar = [NSURL URLWithString:@"http://www.apple.com/"];

urlRequest = [NSURLRequest requestWithURL:urlForCalendar];
urlConnection = [[NSURLConnection alloc] initWithRequest:urlRequest delegate:self startImmediately:NO];

NSRunLoop* runLoop = [NSRunLoop currentRunLoop];
[urlConnection scheduleInRunLoop:runLoop forMode:NSRunLoopCommonModes];
[urlConnection start];

但是,委托回调永远不会被调用。

编辑: 对于将来可能遇到类似问题的任何人,经过一番尝试弄清楚它为什么不起作用之后,我并没有运行循环。所以最后3行代码实际上应该是:

NSRunLoop* runLoop = [NSRunLoop currentRunLoop];   
[urlConnection scheduleInRunLoop:runLoop forMode:NSRunLoopCommonModes];
[urlConnection start];
[runLoop run];

【问题讨论】:

  • 我不使用 [NSURLConnection sendAsynchronousRequest...] 的原因是我想使用 NSURLConnection 的委托方法,因为它们提供了很大的灵活性
  • 您确定在下载期间保持线程处于活动状态吗?
  • 你不需要使用 NSURLConnection 在后台线程上运行。下载已经在后台线程上,但委托方法将在您创建连接的线程上运行(应该是主线程)。你不需要搞乱运行循环或线程,除非返回结果本身的处理速度足够慢以至于它需要在后台。

标签: ios objective-c multithreading nsurlconnection nsrunloop


【解决方案1】:

您不会运行您创建的线程的运行循环,因此您添加到运行循环的连接永远不会得到服务,并且您永远不会收到任何回调。

通常您只想在主线程上处理回调,然后在需要繁重处理时将结果推送到后台线程。

只要你运行运行循环并在下载完成后正确整理,你就可以做你目前正在做的事情。

【讨论】:

  • 是的,刚刚发现,如果以后有人遇到这个问题,会更新帖子。
  • 很公平,但你也应该接受正确的答案;-)
猜你喜欢
  • 2014-08-27
  • 2012-05-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-02-08
  • 2015-05-24
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多