网络开始---多线程---线程间的通信(掌握)(五)
1 #import "HMViewController.h"
2
3 @interface HMViewController ()
4 @property (weak, nonatomic) IBOutlet UIImageView *imageView;
5 @end
6
7 @implementation HMViewController
8
9 - (void)viewDidLoad
10 {
11 [super viewDidLoad];
12 // Do any additional setup after loading the view, typically from a nib.
13 }
14
15 //点击下载图片 下载图片是耗时操作,放到子线程中执行 创建一个新的线程执行下载图片
16 - (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
17 {
18 //创建线程
19 [self performSelectorInBackground:@selector(download) withObject:nil];
20 }
21
22 /**
23 * 下载图片
24 */
25 - (void)download
26 {
27
28 NSLog(@"download---%@", [NSThread currentThread]);
29
30 // 1.要下载的图片地址url
31 NSString *urlStr = @"http://d.hiphotos.baidu.com/image/pic/item/37d3d539b6003af3290eaf5d362ac65c1038b652.jpg";
32
33 NSURL *url = [NSURL URLWithString:urlStr];
34
35 // 2.根据地址下载图片的二进制数据(这句代码最耗时)
36 NSLog(@"---begin"); //二进制数据
37 NSData *data = [NSData dataWithContentsOfURL:url];
38 NSLog(@"---end");
39
40 // 3.设置图片 用二进制数据设置图片
41 UIImage *image = [UIImage imageWithData:data];
42
43 //在子线程中下载图片,下载完成后要回到主线程去修改UI界面,牵扯到主线程与子线程之间的来回穿梭
44 // 4.回到主线程,刷新UI界面(为了线程安全) 就是把图片放上去
45 [self performSelectorOnMainThread:@selector(downloadFinished:) withObject:image waitUntilDone:NO];
46 //后面的YES是指回到主线程设置图片,代码在这里一直等待,等到图片设置好再往下执行
47 //NO则表示回到主线程设置图片,代码继续往下执行,不管图片有没有设置好
48
49
50 //可以给任意线程传东西,线程间的通信 object就是你要传的对象,就是你想要设置的东西
51 // [self performSelector:@selector(downloadFinished:) onThread:[NSThread mainThread] withObject:image waitUntilDone:YES];
52
53 //和主线程通信,设置UI界面图片
54 // [self.imageView performSelectorOnMainThread:@selector(setImage:) withObject:image waitUntilDone:YES];
55
56 NSLog(@"-----done----");
57 }
58
59 /**
60 * 设置这个图片是在主线程中执行的
61 *
62 * @param image <#image description#>
63 */
64 - (void)downloadFinished:(UIImage *)image
65 {
66 self.imageView.image = image;
67
68 NSLog(@"downloadFinished---%@", [NSThread currentThread]);
69 }
70
71 @end