咱们先从 NSURLConnection 作一个get请求:php
- (void)reqConnection { NSLog(@"异步请求测试开始..."); NSURL *url = [NSURL URLWithString:@"http://ip.taobao.com/service/getIpInfo.php?ip=myip"]; NSURLRequest *request = [NSURLRequest requestWithURL:url]; NSLog(@"立刻进行异步链接请求url的数据"); [NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue currentQueue] completionHandler:^(NSURLResponse * _Nullable response, NSData * _Nullable data, NSError * _Nullable connectionError) {//[NSOperationQueue currentQueue]决定block在哪一个队列执行 NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:nil]; NSLog(@"data:%@",dict); if (data.length > 0 && connectionError == nil) { NSLog(@"%lu字节的数据被返回",(unsigned long)data.length); }else if (connectionError == nil && data.length == 0) { NSLog(@"没有数据返回。。"); }else if (connectionError != nil) { NSLog(@"返回错误"); } }]; NSLog(@"异步请求测试完成。。"); }
抛开原理不说,单从请求方式来讲和 AF里的 :html
//startImmediately 是否当即开始 self.connection = [[[NSURLConnection alloc] initWithRequest:self.request delegate:self startImmediately:NO] autorelease]; assert(self.connection != nil); for (NSString * mode in self.actualRunLoopModes) { [self.connection scheduleInRunLoop:[NSRunLoop currentRunLoop] forMode:mode]; } [self.connection start];
来分析思考下 有什么区别:最上面的用的是block,下面这个用的是代理:网络
@implementation ViewController - (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response{ NSLog(@"接收到请求:%@",response); } - (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data{ NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:nil]; NSLog(@"didReceiveData dict:%@",dict); } - (void)viewDidLoad { [super viewDidLoad]; NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:@"http://ip.taobao.com/service/getIpInfo.php?ip=myip"]]; NSURLConnection *connection = [[NSURLConnection alloc] initWithRequest:request delegate:self startImmediately:NO]; [connection start];
接下来看看 这里所谓的 runloop都在干吗?多线程
for (NSString * mode in self.actualRunLoopModes) { [self.connection scheduleInRunLoop:[NSRunLoop currentRunLoop] forMode:mode]; }
**能够将NSTimer手动加入NSRunLoop,Cocoa库也为其它一些类提供了能够手动加入NSRunLoop的方法,这些类有NSPort、NSStream、NSURLConnection、NSNetServices,方法都是[scheduleInRunLoop:forMode:]形式。我暂时只介绍下最经常使用的NSURLConnection类,看看如何把NSURLConnection的网络下载加入到其它线程的run loop去运行。异步
若是NSURLConnection是在主线程中启动的,实际上它就在主线程中运行 -- 并不是启动的另外的线程,但又具有异步运行的特性,这个确实是run loop的巧妙所在。若是对run loop有了初步的了解和概念后,实际上就能明白NSURLConnection的运行,实际也是须要当前线程具有run loop。oop
如何让NSURLConnection在子线程中运行,参考资料:https://blog.csdn.net/lengshengren/article/details/12905697测试
多线程:http://www.javashuo.com/article/p-xtgdggjj-hw.htmlurl
为何别人都这么经常使用多线程,而本身用的却不多,因此好好留心 ,多思考 多用。.net