iOS NSURLConnection 和 dispatch_async 错误的使用方法,导致回调方法无法调用
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, ), ^{
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:[NSURL URLWithString:urlStr] cachePolicy:NSURLRequestReloadIgnoringLocalCacheData timeoutInterval:CONNECTIONT_TIMEOUT];
NSString *encodedStr = [body stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
NSData *sendData = [encodedStr dataUsingEncoding:NSUTF8StringEncoding allowLossyConversion:YES];
NSString *dataLengthStr =[NSString stringWithFormat:@"%lu",(unsigned long)[sendData length]];
[request setValue:dataLengthStr forHTTPHeaderField:@"Content-Length"];
[request setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"];
[request setHTTPMethod:@"POST"];
[request setHTTPBody:sendData];
self.connection = [NSURLConnection connectionWithRequest:request delegate:self];
});
这是一个在主线程中执行的代码,执行结果有问题,无法执行网络回调函数。
原因如下:对于connectionWithRequest这个函数在官方文档下有以下说明:
Delegate methods are called on the same thread that called this method.
这就是说,delegate的消息会发送到调用connectionWithRequest方法的线程中去。如果线程结束了,比如这里就是这样,那么,系统就不会调用相应方法,即使delegate对象本身是存在的!
改正方法很简单,有2种
1.把网络请求发送代码放到主线程,就是不使用dispatch_async
2.在dispatch_async 块的结尾处调用
NSRunLoop *loop = [NSRunLoop currentRunLoop]; [loop run];
当connection完成回调后,会把自己(source)从runloop中移除,这样这个runloop中就没有任何source和timer了,这个runloop会自动停止,相关线程自动结束。
下面是关于run方法的说明,可见,如果没有input source 和timer 加入nsrunloop,这个run方法会立即返回的(这个经过了测试,也十分重要!)。总结下就是,在一个runloop中还有source时,如果调用了run,那么当runloop的source都没了时,这个run方法会自动返回!
If no input sources or timers are attached to the run loop, this method exits immediately; otherwise, it runs the receiver in the NSDefaultRunLoopMode by repeatedly invoking runMode:beforeDate:. In other words, this method effectively begins an infinite loop that processes data from the run loop’s input sources and timers.
再看看runloop的说明
The NSRunLoop class declares the programmatic interface to objects that manage input sources. An NSRunLoop object processes input for sources such as mouse and keyboard events from the window system, NSPort objects, and NSConnection objects. An NSRunLoop object also processes NSTimer events.
这里说明,nsrunloop主要处理2种消息,一种是input source 一种是timer(注意,nsobject中的performSelector的一系列函数就是利用timer放入到runloop中的),而input source分为4种,分别是鼠标消息,键盘消息,port消息(不太明白),nsconnection (不仅仅是网络连接)消息。
另外还需要注意 You should never try to call the methods of an NSRunLoop object running in a different thread, as doing so might cause unexpected results. 也就是说,不要在其他线程中通过调用 runloop对象让runloop停止!必须放到自己的线程中做,这个错误很容易犯。
这个错误提醒我,在使用dispatch_async时,如果没有特殊操作,相关线程会在block结束后立即退出,仅仅靠系统自动加入的input source(比如这里的nsurlconnection),是无法使线程继续存活的,因为加入input source或timer 后还需要我们启动 runloop才行。除了主线程,系统不会为你自动启动runloop的。
iOS NSURLConnection 和 dispatch_async 错误的使用方法,导致回调方法无法调用的更多相关文章
- iOS开发--UIButton 设置圆角 边框颜色 点击回调方法
UIButton *signBtn = [UIButton buttonWithType:UIButtonTypeCustom]; signBtn.frame = CGRectMake(, , , ) ...
- Java回调方法详解
回调在维基百科中定义为: 在计算机程序设计中,回调函数,是指通过函数参数传递到其他代码的,某一块可执行代码的引用. 其目的是允许底层代码调用在高层定义的子程序. 举个例子可能更明白一些:以Androi ...
- java回调方法、钩子方法以及模板方法模式
在面向对象的语言中,回调则是通过接口或抽象类来实现的,我们把实现这种接口的类称为回调类,回调类的对象称为回调对象,其处理事件的方法叫做回调方法.(摘自百度百科) 那么通过上面那句话将百度百科中的&qu ...
- iOS - NSURLConnection 网络请求
前言 @interface NSURLConnection : NSObject class NSURLConnection : NSObject DEPRECATED: The NSURLConne ...
- iOS 真机测试错误“The application bundle does not contain a valid identifier”
iOS 真机测试错误"The application bundle does not contain a valid identifier" 真机测试的时候报错:"The ...
- iOS开发中常见bug!(内附解答方法)
序言 你是否曾经修复了一个 bug ,随后又发现了一个跟刚修复 bug 有关的 bug ,又或是修复 bug 的方式引起了另一个 bug ? 然而这些问题是绝佳的学习机会.所以我们怎样尽可能多地从修复 ...
- iOS NSURLConnection使用详解
一.整体介绍 NSURLConnection是苹果提供的原生网络访问类,但是苹果很快会将其废弃,且由NSURLSession(iOS7以后)来替代.目前使用最广泛的第三方网络框架AFNetworkin ...
- iOS 真机测试错误“The application could not be verified”
iOS 真机测试错误"The application could not be verified" 真机测试的时候报错:"The application could no ...
- iOS之友盟错误统计解决
http://www.cocoachina.com/ios/20150720/12627.html http://lieyunye.github.io/blog/2013/09/10/how-to-a ...
随机推荐
- hdu1507二分匹配
1 //hdu1507 挺不错的题 #include<stdio.h> #include<string.h> #define INF 99999999 struct node ...
- 【POJ 3320】Jessica's Reading Problemc(尺取法)
题 题意 P个数,求最短的一段包含P个数里所有出现过的数的区间. 分析 尺取法,边读边记录每个数出现次数num[d[i]],和不同数字个数n个. 尺取时,l和r 代表区间两边,每次r++时,d[r]即 ...
- 【ZOJ 1221】Risk
题 题意 给你20个城市的相邻关系,求给定任意两个城市的最短距离 分析 求任意两个城市最短距离,就是用floyd算法,我脑残忘记了k是写在最外层的. 代码 #include<stdio.h> ...
- MVC模式的学生信息增删改查
准备:建一个名为 userdb的数据库.建一个student表,有stuid,stuname,gender三个字段.其中stuid为主键.j加入相应的驱动包,相应的JSTL标签 先看目录结构 代码: ...
- jboss7.1.1配置mysql数据源
http://blog.csdn.net/msz1992/article/details/8826754 #1.到http://www.mysql.com/downloads/connector/j/ ...
- php中静态变量和静态方法
1,静态变量:所有对象共享的变量成为静态变量.静态变量类似于全局变量,不过全局变量破坏对象的封装性,因此其对应于面向过程:静态变量对应于面向对象. 2,全局变量,全局变量的使用实例如下,声明全局变量时 ...
- Nagios安装部署和介绍(一)
一.软件版本下载 Nagios版本下载地址: http://prdownloads.sourceforge.net/sourceforge/nagios/ http://sourceforge.net ...
- Centos 5.x/6.x 配置163网易yum源
Centos系统默认都是系统自带的yum源,国内用户用yum源安装比较慢,为了提高效率,一般我们会配置国内的yum源.国内比较好的yum源有网易yum源.搜狐yum源等. 我感觉网易的yum源比较好用 ...
- Log4j 2使用教程
Log4j 2的好处就不和大家说了,如果你搜了2,说明你对他已经有一定的了解,并且想用它,所以这里直接就上手了. 1. 去官方下载log4j 2,导入jar包,基本上你只需要导入下面两个jar包就可以 ...
- 网站的PV,UV,IP名词解释
PV:PV 是Page Views的缩写,即页面浏览量,用户每一次对网站中的每个网页访问均被记录一次.注意,访客每刷新一次页面,pv就增加一次. UV:UV是Unique Visitor的缩写,即独立 ...