iOS多線程---GCD中線程的通訊

來源:互聯網
上載者:User

標籤: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中線程的通訊

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.