-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
22 {
23
24 // 在子线程中调用download方法下载图片
25 [self performSelectorInBackground:@selector(download) withObject:nil];
26 }
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
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