使用 NSThread 时未调用 NSURLConnectionDelegate 方法 [英] NSURLConnectionDelegate methods not called when using NSThread

查看:46
本文介绍了使用 NSThread 时未调用 NSURLConnectionDelegate 方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm trying to run a download in a background thread as to not block the main UI thread on iOS, what I did was create a new thread using

[NSThread detachNewThreadSelector:@selector(startDownload) toTarget:downloadObject withObject:nil];

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

Then the following code runs on a background thread:

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

但是,从不调用委托回调.

However, the delegate callbacks are never called.

对于将来可能遇到类似问题的任何人,在试图找出它不起作用的原因之后,我没有运行循环.所以最后三行代码实际上应该是:

For anyone who might come across a similar problem in the future, after a bit of trying to figure out why it wasn't working, I wasn't running the loop. So the last 3 lines of code should actually be:

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

推荐答案

你没有运行你创建的线程的运行循环,所以你添加到运行循环的连接永远不会被服务,你永远不会得到任何回调.

You don't run the run loop of the thread you created, so the connection you add to the run loop is never serviced and you never get any callbacks.

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

Generally you just want to handle the callbacks on the main thread and then push the result to a background thread if heavy processing is required.

只要您运行运行循环并在下载完成后正确整理,您就可以执行当前正在执行的操作.

You can do what you're currently doing though so long as you run the run loop and tidy up properly once the download is complete.

这篇关于使用 NSThread 时未调用 NSURLConnectionDelegate 方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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