zoukankan      html  css  js  c++  java
  • 如何让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 = [[NSOperationQueueallocinit];

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

    [conn setDelegateQueue:queue];

    [conn start];

  • 相关阅读:
    垃圾收集器
    垃圾收集算法
    JVM内存模型
    工厂方法模式
    类加载机制
    六大设计原则
    单例模式
    HFish开源蜜罐搭建
    利用metasploit复现永恒之蓝
    零信任网络初识
  • 原文地址:https://www.cnblogs.com/ritian/p/5291148.html
Copyright © 2011-2022 走看看