iOS开发多线程篇 04 —线程间的通信
iOS开发多线程篇—线程间的通信
一、简单说明
线程间通信:在1个进程中,线程往往不是孤立存在的,多个线程之间需要经常进行通信
线程间通信的体现
1个线程传递数据给另1个线程
在1个线程中执行完特定任务后,转到另1个线程继续执行任务
线程间通信常用方法
- (void)performSelectorOnMainThread:(SEL)aSelector withObject:(id)arg waitUntilDone:(BOOL)wait;
- (void)performSelector:(SEL)aSelector onThread:(NSThread *)thr withObject:(id)arg waitUntilDone:(BOOL)wait;
线程间通信示例 – 图片下载
代码1:
1 //
2 // YYViewController.m
3 // 06-NSThread04-线程间通信
4 //
5 // Created by apple on 14-6-23.
6 // Copyright (c) 2014年 itcase. All rights reserved.
7 //
8
9 #import "YYViewController.h"
10 @interface YYViewController ()
11 @property (weak, nonatomic) IBOutlet UIImageView *iconView;
12 @end
13
14 @implementation YYViewController
15
16 - (void)viewDidLoad
17 {
18 [super viewDidLoad];
19 }
20
21 -(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
22 {
23
24 // 在子线程中调用download方法下载图片
25 [self performSelectorInBackground:@selector(download) withObject:nil];
26 }
27
28
29
30 -(void)download
31 {
32 //1.根据URL下载图片
33 //从网络中下载图片
34 NSURL *urlstr=[NSURL URLWithString:@"fdsf"];
35
36 //把图片转换为二进制的数据
37 NSData *data=[NSData dataWithContentsOfURL:urlstr];//这一行操作会比较耗时
38
39 //把数据转换成图片
40 UIImage *image=[UIImage imageWithData:data];
41
42 //2.回到主线程中设置图片
43 [self performSelectorOnMainThread:@selector(settingImage:) withObject:image waitUntilDone:NO];
44 }
45
46
47
48 //设置显示图片
49 -(void)settingImage:(UIImage *)image
50 {
51 self.iconView.image=image;
52 }
53
54 @end
代码2:
1 //
2 // YYViewController.m
3 // 06-NSThread04-线程间通信
4 //
5 // Created by apple on 14-6-23.
6 // Copyright (c) 2014年 itcase. All rights reserved.
7 //
8
9 #import "YYViewController.h"
10 #import <NSData.h>
11
12 @interface YYViewController ()
13 @property (weak, nonatomic) IBOutlet UIImageView *iconView;
14 @end
15
16 @implementation YYViewController
17
18 - (void)viewDidLoad
19 {
20 [super viewDidLoad];
21 }
22
23
24 -(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
25 {
26 // 在子线程中调用download方法下载图片
27
28 [self performSelectorInBackground:@selector(download) withObject:nil];
29 }
30
31
32 -(void)download
33 {
34
35 //1.根据URL下载图片
36 //从网络中下载图片
37 NSURL *urlstr=[NSURL URLWithString:@"fdsf"];
38
39 //把图片转换为二进制的数据
40 NSData *data=[NSData dataWithContentsOfURL:urlstr];//这一行操作会比较耗时
41
42 //把数据转换成图片
43 UIImage *image=[UIImage imageWithData:data];
44
45 //2.回到主线程中设置图片
46 //第一种方式
47 // [self performSelectorOnMainThread:@selector(settingImage:) withObject:image waitUntilDone:NO];
48
49 //第二种方式
50 // [self.imageView performSelector:@selector(setImage:) onThread:[NSThread mainThread] withObject:image waitUntilDone:NO];
51
52 //第三种方式
53 [self.iconView performSelectorOnMainThread:@selector(setImage:) withObject:image waitUntilDone:NO];
54 }
55
56
57 //设置显示图片
58 //-(void)settingImage:(UIImage *)image
59 //{
60 // self.iconView.image=image;
61 //}
62
63 @end