After a child thread's task is completed, it is sometimes necessary to go back from the child thread to the main thread and refresh the UI. Returning to the main thread from a child thread has previously written a method:
[Self.imageview performselectoronmainthread: @selector (setimage:) withobject:image Waituntildone:no];
Now GCD provides a way to:
Dispatch_async (Dispatch_get_main_queue (), ^{ Self.imageView.image=image; });
Example code:
////VIEWCONTROLLER.M//gcdtest////Created by login 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 (@"main thread----%@", [Nsthread mainthread]);}-(void) Touchesbegan: (nsset*) touches withevent: (Uievent *)Event{ //1 Get a global queuedispatch_queue_t queue = Dispatch_get_global_queue (Dispatch_queue_priority_default,0); //2 Add a task to the queue to executeDispatch_async (Queue, ^{ //Print the current threadNSLog (@"%@", [Nsthread CurrentThread]); //3. Download pictures from the webNsurl *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]; //TipsNSLog (@"Picture Loading Complete"); //4. Back to the main thread, show pictures//[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
Printing results:
2017-06-16 17:55:45.848 gcdtest[15011:2269875] Main thread----<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] Picture loading complete
2017-06-16 17:56:43.463 gcdtest[15011:2269875] <nsthread:0x60800007f600>{number = 1, name = main}
This article references:http://www.cnblogs.com/wendingding/p/3807265.html
iOS multi-threaded---GCD threads communication