NSURLConnection和NSRunLoop
生活随笔
收集整理的這篇文章主要介紹了
NSURLConnection和NSRunLoop
小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
主線程中創(chuàng)建一個(gè)NSURLConnection并異步運(yùn)行
[self performSelectorOnMainThread:@selector(start) withObject:nil waitUntilDone:YES]; - (void)start {//step 1:請(qǐng)求地址NSURL *url = [NSURL URLWithString:@"www.2cto.com"];//step 2:實(shí)例化一個(gè)requestNSURLRequest *request =[NSURLRequest requestWithURL:url cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:30.0];//step 3:創(chuàng)建鏈接self.connection = [[NSURLConnection alloc] initWithRequest:request delegate:self];//直接執(zhí)行了if (self.connection) {NSLog(@"鏈接成功");}else {NSLog(@"鏈接失敗");} }問(wèn)題:
當(dāng)前線程是主線程
創(chuàng)建的NSURLConnection實(shí)例執(zhí)行在主線程。主線程有一個(gè)執(zhí)行的runloop實(shí)例來(lái)支持NSURLConnection的異步執(zhí)行,
此時(shí)runloop的執(zhí)行模式為NSDefaultRunLoopMode,這樣的mode下,假設(shè)主線程執(zhí)行拖動(dòng)操作,runloop不處理NSURLConnection的回調(diào)事件。
由于拖動(dòng)操作發(fā)生過(guò)程中。使當(dāng)前線程的runloop執(zhí)行在UITrackingRunLoopMode模式下,這樣的模式下的runloop會(huì)暫定處理其它事件(異步請(qǐng)求回調(diào)、timer事件等)。
解決方法,改動(dòng)代碼為:
[self performSelectorOnMainThread:@selector(start) withObject:nil waitUntilDone:YES]; - (void)start {//step 1:請(qǐng)求地址NSURL *url = [NSURL URLWithString:@"www.2cto.com"];//step 2:實(shí)例化一個(gè)requestNSURLRequest *request =[NSURLRequest requestWithURL:url cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:30.0];//step 3:創(chuàng)建鏈接self.connection = [[NSURLConnection alloc] initWithRequest:request delegate:self startImmediately:NO];//臨時(shí)不執(zhí)行[connection scheduleInRunLoop:[NSRunLoop currentRunLoop] forMode:NSRunLoopCommonModes];//用NSRunLoopCommonModes[connection start]; if (self.connection) {NSLog(@"鏈接成功");}else {NSLog(@"鏈接失敗");} }
轉(zhuǎn)載于:https://www.cnblogs.com/claireyuancy/p/6916333.html
總結(jié)
以上是生活随笔為你收集整理的NSURLConnection和NSRunLoop的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: 【转】前端开发流程
- 下一篇: Javascript编码规范,好的代码从