iOS,NSURLConnection:在不同的线程上委托回调? [英] iOS, NSURLConnection: Delegate Callbacks on Different Thread?

查看:86
本文介绍了iOS,NSURLConnection:在不同的线程上委托回调?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何让NSURLConnection从不同的线程而不是主线程调用它的委托方法。我正在尝试使用scheduleInRunLoop:forMode:但似乎没有做我想要的。

How can I get NSURLConnection to call it's delegate methods from a different thread instead of the main thread. I'm trying to mess around with the scheduleInRunLoop:forMode:but doesn't seem to do what I want.

我必须下载一个大文件并且它会中断主线程如此频繁,以至于正在发生的一些渲染开始变得不稳定。

I have to download a large file and it interrupts the main thread so frequently that some rendering that is happening starts getting choppy.

NSURLRequest * request = [NSURLRequest requestWithURL:url];
NSURLConnection * connection = [[NSURLConnection alloc] initWithRequest:request delegate:self startImmediately:NO];
NSRunLoop * loop = [NSRunLoop currentRunLoop];
NSLog(@"loop mode: %@",[loop currentMode]);
[connection scheduleInRunLoop:[NSRunLoop currentRunLoop] forMode:NSRunLoopCommonModes];
[connection start];

另一件我看不到的是模式只记录了两种模式所以真的不太值得测试。

The other thing I don't see much of is "Modes" There are only two modes documented so not much really to test with.

任何想法?

谢谢

推荐答案

有几种选择:


  1. 在执行委托方法时,使用 dispatch_async

  2. 在后台线程上开始计划连接。

你可以这样做:

// all the setup comes here
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
    NSRunLoop *loop = [NSRunLoop currentRunLoop];
    [connection scheduleInRunLoop:loop forMode:NSRunLoopCommonModes];
    [loop run]; // make sure that you have a running run-loop.
});

如果您想要保证您正在运行哪个线程,请将该呼叫替换为 dispatch_get_global_queue()恰当。

If you want a guarantee on which thread you're running, replace the call to dispatch_get_global_queue() appropriately.

这篇关于iOS,NSURLConnection:在不同的线程上委托回调?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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