NSURLConnection和NSRunLoop

來源:互聯網
上載者:User

標籤:object-c   ios開發   線程   


主線程中建立一個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(@"連結失敗");    }}





NSURLConnection和NSRunLoop

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.