標籤:dispatch ted mic tun datawit imageview pat http main
在子線程的任務完成後,有時候需要從子線程回到主線程,重新整理UI。 從子線程中回到主線程,以前已經寫過一種方法:
[self.imageView performSelectorOnMainThread:@selector(setImage:) withObject:image waitUntilDone:NO];
現在GCD又提供了一種方法:
dispatch_async(dispatch_get_main_queue(), ^{ self.imageView.image=image; });
範例程式碼:
//// ViewController.m// GCDTest//// Created by 登 on 2017/6/16.// Copyright ? 2017年 登. All rights reserved.//#import "ViewController.h"@interface ViewController ()@property (weak, nonatomic) IBOutlet UIImageView *imageView;@end@implementation ViewController- (void)viewDidLoad{ [super viewDidLoad]; NSLog(@"主線程----%@",[NSThread mainThread]);}-(void)touchesBegan:(NSSet*)touches withEvent:(UIEvent *)event{ //1 擷取一個全域隊列 dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0); // 2 把任務添加到隊列中執行 dispatch_async(queue, ^{ //列印當前的線程 NSLog(@"%@",[NSThread currentThread]); //3.從網路下載圖片 NSURL *urlStr = [NSURL URLWithString:@"http://h.hiphotos.baidu.com/baike/w%3D268/sign=30b3fb747b310a55c424d9f28f444387/1e30e924b899a9018b8d3ab11f950a7b0308f5f9.jpg"]; NSData *data = [NSData dataWithContentsOfURL:urlStr]; UIImage *image = [UIImage imageWithData:data]; //提示 NSLog(@"圖片載入完畢"); //4.回到主線程,展示圖片 // [self.imageView performSelectorOnMainThread:@selector(setImageView:) withObject:image waitUntilDone:NO]; dispatch_async(dispatch_get_main_queue(), ^{ _imageView.image = image; NSLog(@"%@",[NSThread currentThread]); }); }); }- (void)didReceiveMemoryWarning { [super didReceiveMemoryWarning];}@end
列印結果:
2017-06-16 17:55:45.848 GCDTest[15011:2269875] 主線程----<NSThread: 0x60800007f600>{number = 1, name = main}
2017-06-16 17:56:43.391 GCDTest[15011:2269966] <NSThread: 0x60000026b980>{number = 3, name = (null)}
2017-06-16 17:56:43.463 GCDTest[15011:2269966] 圖片載入完畢
2017-06-16 17:56:43.463 GCDTest[15011:2269875] <NSThread: 0x60800007f600>{number = 1, name = main}
本文參考:http://www.cnblogs.com/wendingding/p/3807265.html
iOS多線程---GCD中線程的通訊