NSURLConnection和NSRunLoop

本文探讨了在主线程中使用NSURLConnection进行异步请求时遇到的问题,即当主线程处于特定模式(如拖动操作)时,无法处理NSURLConnection的回调事件。文章提供了修改后的代码实现,确保在不同模式下都能正确处理请求。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >


主线程中创建一个NSURLConnection并异步运行

[self performSelectorOnMainThread:@selector(start) withObject:nil waitUntilDone:YES];
- (void)start
{
    //step 1:请求地址
    NSURL *url = [NSURL URLWithString:@"www.2cto.com"];
    //step 2:实例化一个request
    NSURLRequest *request =[NSURLRequest requestWithURL:url cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:30.0];
    //step 3:创建链接
    self.connection = [[NSURLConnection alloc] initWithRequest:request delegate:self];//直接执行了
    if (self.connection) {
        NSLog(@"链接成功");
    }else {
        NSLog(@"链接失败");
    }
}

问题:
当前线程是主线程
创建的NSURLConnection实例执行在主线程。主线程有一个执行的runloop实例来支持NSURLConnection的异步执行,
此时runloop的执行模式为NSDefaultRunLoopMode,这样的mode下,假设主线程执行拖动操作,runloop不处理NSURLConnection的回调事件。
由于拖动操作发生过程中。使当前线程的runloop执行在UITrackingRunLoopMode模式下,这样的模式下的runloop会暂定处理其它事件(异步请求回调、timer事件等)。


解决方法,改动代码为:

[self performSelectorOnMainThread:@selector(start) withObject:nil waitUntilDone:YES];
- (void)start
{
    //step 1:请求地址
    NSURL *url = [NSURL URLWithString:@"www.2cto.com"];
    //step 2:实例化一个request
    NSURLRequest *request =[NSURLRequest requestWithURL:url cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:30.0];
    //step 3:创建链接
    self.connection = [[NSURLConnection alloc] initWithRequest:request delegate:self startImmediately:NO];//临时不执行
    [connection scheduleInRunLoop:[NSRunLoop currentRunLoop] forMode:NSRunLoopCommonModes];//用NSRunLoopCommonModes
    [connection start];    
    if (self.connection) {
        NSLog(@"链接成功");
    }else {
        NSLog(@"链接失败");
    }
}





转载于:https://www.cnblogs.com/claireyuancy/p/6916333.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值