可以有两个办法让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 alloc] initWithRequest:request delegate:self startImmediately:NO];

[conn setDelegateQueue:queue];

[conn start];

如何让NSURLConnection在子线程中运行的更多相关文章

  1. 让NSURLConnection在子线程中运行

    可以有两个办法让NSURLConnection在子线程中运行,即将NSURLConnection加入到run loop或者NSOperationQueue中去运行. 前面提到可以将NSTimer手动加 ...

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

    可以有两个办法让NSURLConnection在子线程中运行,即将NSURLConnection加入到run loop或者NSOperationQueue中去运行. 前面提到可以将NSTimer手动加 ...

  3. 【转载】Delphi7从子线程中发送消息到主线程触发事件执行

    在对数据库的操作时,有时要用一个子线程来进行后台的数据操作.比如说数据备份,转档什么的.在主窗口还能同是进行其它操作.而有时后台每处理一个数据文件,要向主窗口发送消息,让主窗口实时显示处理进度在窗口上 ...

  4. 在子线程中new Handler报错--Can't create handler inside thread that has not called Looper.prepare()

    在子线程中new一个Handler为什么会报以下错误? java.lang.RuntimeException:  Can't create handler inside thread that has ...

  5. 在子线程中使用runloop,正确操作NSTimer计时的注意点 三种可选方法

    一直想写一篇关于runloop学习有所得的文章,总是没有很好的例子.游戏中有一个计时功能在主线程中调用: 1 + (NSTimer *)scheduledTimerWithTimeInterval:( ...

  6. Android开发UI之在子线程中更新UI

    转自第一行代码-Android Android是不允许在子线程中进行UI操作的.在子线程中去执行耗时操作,然后根据任务的执行结果来更新相应的UI控件,需要用到Android提供的异步消息处理机制. 代 ...

  7. .Net主线程扑捉子线程中的异常

    首先看一段C#代码:运行后发现主线程通过try{}catch{}是不能扑捉子线程中的抛出来的异常. 代码 );        }        public void run()        {   ...

  8. iOS开发之线程间的MachPort通信与子线程中的Notification转发

    如题,今天的博客我们就来记录一下iOS开发中使用MachPort来实现线程间的通信,然后使用该知识点来转发子线程中所发出的Notification.简单的说,MachPort的工作方式其实是将NSMa ...

  9. 【转】在子线程中new Handler报错--Can't create handler inside thread that has not called Looper.prepare()

    在子线程中new一个Handler为什么会报以下错误? java.lang.RuntimeException:  Can't create handler inside thread that has ...

随机推荐

  1. lua 计算字符串字符个数“中文字算一个字符”

    local function GetStringWordNum(str) local fontSize = local lenInByte = #str local count = local i = ...

  2. dataAdapter

    public static class DataAdapter { /// <summary> /// DataRow转换成Hash对象 /// </summary> /// ...

  3. JS操作DOM的一些常用方法

    getElementById():获取有指定惟一ID属性值文档中的元素 getElementsByName(name):返回的是数组 getElementsByTagName():返回具有指定标签名的 ...

  4. day05_20190127_python之路——常用模块

    什么是模块? 常见的场景:一个模块就是一个包含了python定义和声明的文件,文件名就是模块名字加上.py的后缀.模块的本质:就是封装了很多很多函数.功能的一个文件 但其实import加载的模块分为四 ...

  5. CentOS LiveCD、LiveDVD、BinDVD、netinstall、minimal版区别在哪里

    BinDVD版——就是普通安装版,需安装到计算机硬盘才能用,bin一般都比较大,而且包含大量的常用软件,安装时无需再在线下载(大部分情况). minimal版——这个镜像文件用于安装一个非常基本的 C ...

  6. nginx 自动填充index.php

    if (!-e $request_filename) { rewrite ^/(.+?\.php)/?(.*)$ /$/$ last; rewrite ^/(.*)$ /index.php/$ las ...

  7. yum 安装nginx(配置开机启动)

    yum install -y nginx 通过yum安装的时候提示下面的错误 [root@localhost yum.repos.d]# yum install nginx 已加载插件:fastest ...

  8. python实现定时发送消息

    #!/usr/bin/env python#-*- coding:utf-8 -*- @Author : wujf @Time:2018/8/21 15:59# 自动发送消息from threadin ...

  9. jenkins+testlink+python搭建自动化测试环境

    一. 环境搭建 jenkins安装与配置请参考我的另一篇博文:https://www.cnblogs.com/wuxunyan/p/9592953.html testlink安装请参考博文:https ...

  10. [caffe] caffe训练tricks

    Tags: Caffe Categories: Tools/Wheels --- 1. 将caffe训练时将屏幕输出定向到文本文件 caffe中自带可以画图的工具,在caffe路径下: ./tools ...