码迷,mamicode.com
首页 > 移动开发 > 详细

iOS开发小功能之十一:线程间的通信(3种方式)

时间:2016-05-13 07:39:44      阅读:127      评论:0      收藏:0      [点我收藏+]

标签:

三种方法都是通过touchesBegin监听屏幕的触摸实现

一、performSelector方式

 1 #import "ViewController.h"
 2 @interface ViewController ()
 3 @property (weak, nonatomic) IBOutlet UIImageView *imageView;
 4 @end
 5 @implementation ViewController
 6 - (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
 7 {
 8     //放入子线程
 9     [self performSelectorInBackground:@selector(download3) withObject:nil];
10 }
11 
12 //下载放入子线程,显示图片应该放在主线程!!!否则会导致刷新问题
13 - (void)download3
14 {
15     //图片的网络路径
16     NSURL *url = [NSURL URLWithString:@"http://ww2.sinaimg.cn/mw690/63e6fd01jw1f3f3rf75goj20qo0zkagy.jpg"];
17     //下载图片数据
18     NSData *data = [NSData dataWithContentsOfURL:url];
19     
20     //生成图片
21     UIImage *image = [UIImage imageWithData:data];
22     //回到主线程显示图片方法一:
23 //    [self performSelectorOnMainThread:@selector(showImage:) withObject:image waitUntilDone:YES];
24     //回到主线程显示图片方法二:
25     //waitUntilDone:表示是否等待主线程做完事情后往下走,YES表示做完后执行下面事,NO表示跟下面事一起执行
26     [self.imageView performSelectorOnMainThread:@selector(setImage:) withObject:image waitUntilDone:YES];
27     //回到主线程显示图片方法三:
28     [self.imageView performSelector:@selector(setImage:) onThread:[NSThread mainThread] withObject:image waitUntilDone:YES];
29 }
30 //主线程显示图片
31 - (void)showImage:(UIImage *)image
32 {
33     self.imageView.image = image;
34 }

 

二、GCD方式

 1 - (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
 2 {
 3     dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
 4         //图片的网络途径
 5         NSURL *url = [NSURL URLWithString:@"http://ww2.sinaimg.cn/mw1024/75614297jw1f34e5llyz4j20qo0zj0zl.jpg"];
 6         //加载图片
 7         NSData *data = [NSData dataWithContentsOfURL:url];
 8         //生成图片
 9         UIImage *image = [UIImage imageWithData:data];10         //回到主线程
11         dispatch_async(dispatch_get_main_queue(), ^{
12             self.imageView.image = image;
13         });
14     });
15     
16 }

 

三、operation方式(此种方式更具有面向对象特性!)

 

 1 - (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
 2 {
 3     //直接开始子线程执行任务
 4     [[[NSOperationQueue alloc] init] addOperationWithBlock:^{
 5         NSURL *url = [NSURL URLWithString:@"http://ww4.sinaimg.cn/mw690/63e6fd01jw1ezxz499hy5j21gt0z94qq.jpg"];
 6         NSData *data = [NSData dataWithContentsOfURL:url];
 7         UIImage *image = [UIImage imageWithData:data];
 8         //回到主线程
 9         [[NSOperationQueue mainQueue] addOperationWithBlock:^{
10             //显示图片
11             self.imageView.image = image;
12         }];
13     }];
14 }

 

以上三种方式都需要在main storyboard中拖一个imageView,然后设置自动布!!

iOS开发小功能之十一:线程间的通信(3种方式)

标签:

原文地址:http://www.cnblogs.com/hissia/p/5484724.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!