线程间的通信主要用于主线程与子线程的,也有用于子线程与子线程的
介绍下面几种通信方式
1.利用GCD方式(推荐)
- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event { //开一个子线程 dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{ //下载图片 NSURL *url = [NSURL URLWithString:@"http://e.hiphotos.baidu.com/image/pic/item/14ce36d3d539b600be63e95eed50352ac75cb7ae.jpg"]; NSData *data = [NSData dataWithContentsOfURL:url]; UIImage *img = [UIImage imageWithData:data]; dispatch_async(dispatch_get_main_queue(), ^{ //回到主线程 self.imgVIew.image = img; }); //在这里使用同步还是异步,区别是前者是按顺序依次执行,后者是先执行到最后再回到主线程 NSLog(@"________"); }); }
利用这种方式可以轻松地控制线程间的跳转通信
2.利用系统方法
- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event { //创建子线程 [self performSelectorInBackground:@selector(downLoad) withObject:nil]; } //在子线程中下载图片 - (void)downLoad { NSURL *url = [NSURL URLWithString:@"http://e.hiphotos.baidu.com/image/pic/item/e7cd7b899e510fb34395d1c3de33c895d0430cd1.jpg"]; NSData *data = [NSData dataWithContentsOfURL:url]; UIImage *img = [UIImage imageWithData:data]; //下载完毕,返回给主线程图片 [self.imgVIew performSelector:@selector(setImage:) onThread:[NSThread mainThread] withObject:img waitUntilDone:YES]; }
补充:也可以使用
[self performSelectorOnMainThread:@selector(setImg:) withObject:img waitUntilDone:YES];这个方法返回主线程图片
@selector(这里面其实就是主线程中image属性的set方法)
3.使用NSOperation方式
与GCD类似
- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event { [[[NSOperationQueue alloc] init] addOperationWithBlock:^{ //下载图片 NSURL *url = [NSURL URLWithString:@"http://e.hiphotos.baidu.com/image/pic/item/e7cd7b899e510fb34395d1c3de33c895d0430cd1.jpg"]; NSData *data = [NSData dataWithContentsOfURL:url]; UIImage *img = [UIImage imageWithData:data]; //回到主线程 [[NSOperationQueue mainQueue] addOperationWithBlock:^{ self.imgView.image = img; }]; }]; }