您的位置:首页 > 移动开发 > IOS开发

iOS多线程的初步研究(五)-- 如何让NSURLConnection在子线程中运行

2016-05-28 00:00 483 查看
http://www.cnblogs.com/sunfrog/p/3262624.html

前面提到可以将NSTimer手动加入NSRunLoop,Cocoa库也为其它一些类提供了可以手动加入NSRunLoop的方法,这些类有NSPort、NSStream、NSURLConnection、NSNetServices,方法都是[scheduleInRunLoop:forMode:]形式。我暂时只介绍下最常用的NSURLConnection类,看看如何把NSURLConnection的网络下载加入到其它线程的run loop去运行。

如果NSURLConnection是在主线程中启动的,实际上它就在主线程中运行 -- 并非启动的另外的线程,但又具备异步运行的特性,这个确实是run loop的巧妙所在。如果对run loop有了初步的了解和概念后,实际上就能明白NSURLConnection的运行,实际也是需要当前线程具备run loop。

- (void)scheduleInRunLoop:(NSRunLoop *)aRunLoop forMode:(NSString *)mode; //将加入指定的run loop中运行,必须保证这时NSURLConnection不能启动,否则不起作用了

- (void)unscheduleFromRunLoop:(NSRunLoop *)aRunLoop forMode:(NSString *)mode; //将取消在指定run loop中的运行,实际上就会停止NSURLConnection的运行

下面是如何在其它线程中运行NSURLConnection的主要实现代码:

NSRunLoop *runloop; //global

[self performSelectorInBackground:@selector(thread) withObject:nil]; //启动包含run
loop的线程

NSURLConnection *conn = [[NSURLConnection alloc] initWithRequest:request delegate:self startImmediately:NO]; //注意这时不能先启动NSURLConnection

[conn scheduleInRunLoop:runloop forMode:NSRunLoopCommonModes]; //指定在上面启动的线程中运行NSURLConnection

[conn start]; //启动NSURLConnection

- (void)thread

{

  runloop = [NSRunLoop currentRunLoop]; //设置为当前线程的run loop值

  while (condition)

  {

    [runloop runUntilDate:[NSDate dateWithTimeIntervalSinceNow:1.0]];
//启动run loop


  }

}

 

将NSURLConnection加入到NSOperationQueue中去运行的方式基本类似:

NSOperationQueue *queue = [[NSOperationQueuealloc] init];

NSURLConnection *conn = [[NSURLConnection alloc] initWithRequest:request delegate:self startImmediately:NO]; 

[conn setDelegateQueue:queue];

[conn start];
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: