zoukankan      html  css  js  c++  java
  • NSURLConnection和NSRunLoop


    主线程中创建一个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(@"链接失败");
        }
    }
    





  • 相关阅读:
    POJ 3140 Contestants Division (树dp)
    POJ 3107 Godfather (树重心)
    POJ 1655 Balancing Act (树的重心)
    HDU 3534 Tree (经典树形dp)
    HDU 1561 The more, The Better (树形dp)
    HDU 1011 Starship Troopers (树dp)
    Light oj 1085
    Light oj 1013
    Light oj 1134
    FZU 2224 An exciting GCD problem(GCD种类预处理+树状数组维护)同hdu5869
  • 原文地址:https://www.cnblogs.com/claireyuancy/p/6916333.html
Copyright © 2011-2022 走看看