zoukankan      html  css  js  c++  java
  • iOS多线程的初步研究(五)-- 如何让NSURLConnection在子线程中运行

    可以有两个办法让NSURLConnection在子线程中运行,即将NSURLConnection加入到run loop或者NSOperationQueue中去运行。

    前面提到可以将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 allocinitWithRequest:request delegate:self startImmediately:NO]; 

    [conn setDelegateQueue:queue];

    [conn start];

     

  • 相关阅读:
    linux在线安装jdk,tomcat,Nginx
    SpringAOP的实现方式
    Spring整合Mybatis
    基本sql语句
    解决No module named 'sklearn.cross_validation'
    虚拟机中安装redhat8操作系统
    【Linux命令】tcpdump抓包工具
    【Nodejs】Linux系统搭建Nodejs
    【SSL证书配置】tomcat实现SSL证书访问
    【SSL证书配置】腾讯云申请ssl证书,nginx+tomcat配置ssl证书
  • 原文地址:https://www.cnblogs.com/sunfrog/p/3262624.html
Copyright © 2011-2022 走看看