The common usage of iOS development multithreaded article 08-GCD

Source: Internet
Author: User
Tags gcd

The common usage of iOS development multithreaded article-GCD

I. Deferred implementation1. IntroductionThere are 2 ways that iOS typically delays execution

(1) Method of calling NSObject

[Self performselector: @selector (Run) Withobject:nil afterdelay:2.0];

Call the self's Run method after 2 seconds

(2) using the GCD function

Dispatch_after (Dispatch_time (Dispatch_time_now, (int64_t) (2.0 * nsec_per_sec)), Dispatch_get_main_queue (), ^{

Execute the code here asynchronously after 2 seconds ...

});

2. Description

the first method, which is called on that thread, is where run executes (the current thread), usually the main thread.

[Self performselector: @selector (Run) Withobject:nil afterdelay:3.0];

Description: After 3 seconds, execute the Run function

code example:

 1//2//YYVIEWCONTROLLER.M 3//01-GCD common use (deferred execution) 4//5//Created by Apple on 14-6-25. 6//Copyright (c) 2014 itcase. All rights reserved. 7//8 9 #import "YYViewController.h" @interface Yyviewcontroller () @end14 @implementation Yyviewcontroller 21-(void) viewDidLoad18 {[Super viewdidload];20 NSLog (@ "Print thread----%@", [Nsthread CurrentThread]); 22//First method: Delay 3 seconds call the Run function [self performselector: @selector (run) Withobject:nil afterdelay:2.0];24}26-(void ) run27 {NSLog (@ "deferred execution----%@", [Nsthread CurrentThread]);}30-(void) Touchesbegan: (Nsset *) touches withevent: (UIE Vent *) Event32 {33//execute in asynchronous function dispatch_queue_t queue = dispatch_queue_create ("wendingding", 0); Patch_sync (queue, ^{37 [self performselector: @selector (Test) Withobject:nil afterdelay:1.0];38}); NSLog (@ "Async function"),}41-(void) Test42 {NSLog (@ "Asynchronous function deferred execution----%@", [Nsthread CurrentThread]);}45 @end

Description: If the method is executed in an asynchronous function, the method will not be called (BUG?).

the second method,

Dispatch_after (Dispatch_time (Dispatch_time_now, (int64_t) (5.0 * nsec_per_sec)), Dispatch_get_main_queue (), ^{

Methods for deferred execution

});

Description: After 5 seconds, execute the code snippet in block.

Parameter description:

What time to perform this task in this queue.

code example:

 1//2//YYVIEWCONTROLLER.M 3//02-GCD common use (deferred execution 2) 4//5//Created by Apple on 14-6-25. 6//Copyright (c) 2014 itcase. All rights reserved. 7//8 9 #import "YYViewController.h" @interface Yyviewcontroller () @end14 @implementation Yyviewcontroller     22-(void) viewDidLoad18 {[Super viewdidload];20] NSLog (@ "Print current thread---%@", [Nsthread CurrentThread]); 23//deferred execution, second way 24//can arrange its thread (1), home row dispatch_queue_t queue= dispatch_get_main_queue (); dispatch_after  (Dispatch_time (Dispatch_time_now, (int64_t) (5.0 * nsec_per_sec)), queue, ^{27 NSLog (@ "Home row--deferred execution------%@", [Nsthread CurrentThread]); 28}); 29 30//can schedule its thread (2), concurrent queue 31//1. Get global concurrency queue dispatch_queue_t queue1= dispatch_get_ Global_queue (dispatch_queue_priority_default, 0); 33//2. Calculate time for task execution dispatch_time_t When=dispatch_time (DISPATCH_TI   Me_now, (int64_t) (5.0 * nsec_per_sec)); 35//3. At this point in time, execute this task in queue Dispatch_after (when, queue1, ^{37      NSLog (@ "Concurrent queue-deferred execution------%@", [Nsthread CurrentThread]);}40 @end 

Deferred execution: No more writing method is required, and it also passes a queue, and we can specify and schedule its threads.

If the queue is a home column, it is executed on the main thread, and if the queue is a concurrent queue, a new thread is opened and executed in the child thread.

Second, disposable code

1. Implement one-time code

Requirements: Click on the controller only when the first click to print.

Implementation code:

1//2//  YYVIEWCONTROLLER.M 3//  03-GCD common use (one-time code) 4//5//  Created by Apple on 14-6-25.6//  Copyright (c) Itcase 2014. All rights reserved. 7//8  9 #import "YYViewController.h" @interface Yyviewcontroller () @property (nonatomic,assign) BOOL log;13 @e Nd14 @implementation YYViewController16-(void) Touchesbegan: (Nsset *) touches withevent: (uievent *) event18 {19     if (_log==no) {         NSLog (@ "The line code executes only once")         _log=yes;22     }23}24 @end

Cons: This is an object method, and if you create a new controller again, the print code executes because each newly created controller has its own Boolean type, and the newly created default is no, so it is not guaranteed that the row code will be printed only once throughout the program.

2. Use dispatch_once Disposable Code

Use the Dispatch_once function to ensure that a piece of code is executed only 1 times during program operation

Static dispatch_once_t Oncetoken;

Dispatch_once (&oncetoken, ^{

Execute code only 1 times (this is thread-safe by default)

});

The entire program runs, only once.

code example:

1//2//  YYVIEWCONTROLLER.M 3//  03-GCD common use (one-time code) 4//5//  Created by Apple on 14-6-25.6//  Copyright (c) Itcase 2014. All rights reserved. 7//8  9 #import "YYViewController.h" @interface Yyviewcontroller () @property (nonatomic,assign) BOOL log;13 @e Nd14 @implementation YYViewController16//-(void) Touchesbegan: (Nsset *) touches withevent: (uievent *) event18//{19    if (_log==no) {//        NSLog (@ "The line code executes only once"),//        _log=yes;22//    }23//}24-(void) Touchesbegan: ( *) touches withevent: (uievent *) event26 {nsset dispatch_once_t oncetoken;28 dispatch_once     (& Oncetoken, ^{29         NSLog (@ "The line code executes only once");     }32 @end

Effect (the printed code executes only once while the program is running):

Third, queue Group

Requirements: Download two images from the Web and merge the two images into one and display them on the view.

1. The first method

code example:

 1//2//YYVIEWCONTROLLER.M 3//04-GCD basic use (queue Group download image) 4//5//Created by Apple on 14-6-25. 6//Copyright (c) 2014 itcase. All rights reserved. 7//8 9 #import "YYViewController.h" 10//macros define global concurrency queue one by one #define Global_quque Dispatch_get_global_queue (DISPATCH_QUEUE_PR Iority_default, 0) 12//macro definition The home row #define Main_queue dispatch_get_main_queue (), @interface Yyviewcontroller () 16 @ Property (weak, nonatomic) Iboutlet Uiimageview *imageview1;17 @property (weak, nonatomic) Iboutlet Uiimageview *imagevie  W2;18 @property (Weak, nonatomic) Iboutlet uiimageview *imageview3;19 @end21 @implementation YYViewController23 24- (void) VIEWDIDLOAD25 {[Super viewdidload];27}28-(void) Touchesbegan: (Nsset *) touches withevent: (uievent *) event29 {30//Get global concurrent queue//dispatch_queue_t queue= dispatch_get_global_queue (dispatch_queue_priority_default, 0); 32// Get home Row//dispatch_queue_t queue= dispatch_get_main_queue (); 34 35//Picture 1:http://d.hiphotos.baidu.com/baike/c0%3dbaike80%2c5%2c5%2c80%2c26/sign=2b9a12172df5e0fefa1581533d095fcd/ Cefc1e178a82b9019115de3d738da9773912ef00.jpg36//Picture 2:http://h.hiphotos.baidu.com/baike/c0%3dbaike80%2c5%2c5% 2c80%2c26/sign=f47fd63ca41ea8d39e2f7c56f6635b2b/1e30e924b899a9018b8d3ab11f950a7b0308f5f9.jpg37 Dispatch_async ( Global_quque, ^{38//download image 139 UIImage *image1= [self imagewithurl:@] Http://d.hiphotos.baidu.com/baike/c0%3Db Aike80%2c5%2c5%2c80%2c26/sign=2b9a12172df5e0fefa1581533d095fcd/cefc1e178a82b9019115de3d738da9773912ef00.jpg "]; NSLog (@ "Picture 1 download Completed---%@", [Nsthread CurrentThread]); 41 42//Download image 243 UIImage *image2= [self image withurl:@ "http://h.hiphotos.baidu.com/baike/c0%3Dbaike80%2C5%2C5%2C80%2C26/sign= F47fd63ca41ea8d39e2f7c56f6635b2b/1e30e924b899a9018b8d3ab11f950a7b0308f5f9.jpg "];44 NSLog (@" Picture 2 Download Complete---%@ ", [ Nsthread CurrentThread]); 45 46//back to the main thread display picture Dispatch_async (Main_queue, ^{48 NSLog (@ " Show Picture---%@ ", [Nsthread CurrentThread]); self.imageview1.image=image1;50 self.imageview2.image=image2;51//merge two pictures 52 Uigraphicsbeginimagecontextwithoptions (Cgsizemake (+), NO, 0.0), [Image1 Drawinrect:cgrectmake ( 0, 0,];54, [Image2 drawinrect:cgrectmake (0, +),];55 SELF.IMAGEVIEW3.IMAGE=UIGR                Aphicsgetimagefromcurrentimagecontext (); 56//Close context Uigraphicsendimagecontext (); 58 NSLog (@ "Picture merge completed---%@", [Nsthread CurrentThread]); 59}); 60//61}); 62}63 64//Encapsulate a method, pass in a URL parameter, return a network up and down Photo of the Download (UIImage *) Imagewithurl: (NSString *) urlStr66 {nsurl *url=[nsurl urlwithstring:urlstr];68 nsdata *data=[ NSData datawithcontentsofurl:url];69 UIImage *image=[uiimage imagewithdata:data];70 return image;71}72 @end

Display effect:

Print View:

Problem: This method is not efficient, need to wait until the picture 1. Picture 2 is complete after download.

Tip: Using a queue group allows the download of pictures 1 and 2 to be performed simultaneously, and when the two download tasks are completed, they are returned to the main thread for display.

2. Use queue groups to resolve

Steps:

Creating a group

Open a task download image 1

Open a task download Image 2

Simultaneous download image 1\ download Image 2 operation

All tasks in the group are completed, and then go back to the main thread to perform other operations

code example

  1//2//YYVIEWCONTROLLER.M 3//04-GCD basic use (queue Group download image) 4//5//Created by Apple on 14-6-25. 6//Copyright (c) 2014 itcase.  All rights reserved. 7//8 9 #import "YYViewController.h" 10//macros define global concurrency queue one by one #define Global_quque Dispatch_get_global_queue (Dispatch_queu E_priority_default, 0) 12//macro definition The home row #define Main_queue dispatch_get_main_queue (), @interface Yyviewcontrolle R () @property (weak, nonatomic) Iboutlet Uiimageview *imageview1; @property (Weak, nonatomic) Iboutlet Uiimageview *imageview2; @property (Weak, nonatomic) Iboutlet Uiimageview *imageview3; @end @implementation Yyviewcontroller-(void) viewdidload [[Super Viewdidload]; 27} 28-( void) Touchesbegan: (Nsset *) touches withevent: (Uievent *) Event 29 {30//Picture 1:http://d.hiphotos.baidu.com/baike/c0%3 Dbaike80%2c5%2c5%2c80%2c26/sign=2b9a12172df5e0fefa1581533d095fcd/cefc1e178a82b9019115de3d738da9773912ef00.jpg 31//Picture 2:http://h.hiphotos.baidu.com/baike/c0%3dbaike80%2c5%2c5%2c80%2c26/sign=f47fd63ca41ea8d39e2f7c56f6635b2b/ 1e30e924b899a9018b8d3ab11f950a7b0308f5f9.jpg 32 33 34//1. Create a queue group dispatch_group_t group = Dispat Ch_group_create (); 36 37//2. Open a task download image 1 __block UIImage *image1=nil; Dispatch_group_async (Group, Global_quque, ^{image1= [self imagewithurl:@] Http://d.hiphotos.baidu.com/ba ike/c0%3dbaike80%2c5%2c5%2c80%2c26/sign=2b9a12172df5e0fefa1581533d095fcd/ Cefc1e178a82b9019115de3d738da9773912ef00.jpg "]; NSLog (@ "Picture 1 download Completed---%@", [Nsthread CurrentThread]); 42}); 43 44//3. Open a task download Image 2 __block UIImage *image2=nil; Dispatch_group_async (Group, Global_quque, ^{image2= [self imagewithurl:@] Http://h.hiphotos.baidu.com/ba ike/c0%3dbaike80%2c5%2c5%2c80%2c26/sign=f47fd63ca41ea8d39e2f7c56f6635b2b/ 1e30e924b899a9018b8d3ab11f950a7b0308f5f9.jpg "]; NSLog (@ "Picture 2 download Completed---%@", [Nsthread CurrentThread]); 49}); 50 51//SimultaneousLine download picture 1\ download Image 2 Operation 52 53//4. All the tasks in the group are executed, and then go back to the main thread to perform other operations. Dispatch_group_notify (Group,main_queue, ^{55 NSLog (@ "Show Picture---%@", [Nsthread CurrentThread]); Self.imageview1.image=image1; Self.imageview2.image=image2; 58 59//Merge two pictures 60//Note the last parameter is a floating-point number (0.0), do not write 0. Uigraphicsbeginimagecontextwithoptions (Cgsizemake (), No. 0.0); [Image1 drawinrect:cgrectmake (0, 0, 100, 100)]; [Image2 drawinrect:cgrectmake (100, 0, 100, 100)]; Self.imageview3.image=uigraphicsgetimagefromcurrentimagecontext (); 65//Close context uigraphicsendimagecontext (); NSLog (@ "Picture merge completed---%@", [Nsthread CurrentThread]); 69}); (void) Download2image 73 {74//Get global concurrent queue//dispatch_queue_t queue= Dispatch_get_global_queue (DI Spatch_queue_priority_default, 0); 76//Get home Row//dispatch_queue_t queue= dispatch_get_main_queue (); Dispatch_async (Global_quque, ^{80//Download image 1 Bayi UIImage *image1= [self imagewithurl:@ "HTTP://NEWS.BAIDU.COM/Z/RESOURC E/r/image/2014-06-22/2a1009253cf9fc7c97893a4f0fe3a7b1.jpg "]; NSLog (@ "Picture 1 download Completed---%@", [Nsthread CurrentThread]); 83 84//Download Image 2 UIImage *image2= [self imagewithurl:@ "http://news.baidu.com/z/resource/r/image/2014-0 6-22/2a1009253cf9fc7c97893a4f0fe3a7b1.jpg "]; NSLog (@ "Picture 2 download Completed---%@", [Nsthread CurrentThread]); 87 88//Back to main thread display picture Dispatch_async (Main_queue, ^{NSLog (@ "Show Picture---%@", [Nsthread C Urrentthread]); Self.imageview1.image=image1; Self.imageview2.image=image2; 93//Merge two pictures 94 uigraphicsbeginimagecontextwithoptions (Cgsizemake (), NO, 0.0); [Image1 drawinrect:cgrectmake (0, 0, 100, 100)]; [Image2 drawinrect:cgrectmake (0, 0, 100, 100)]; Self.imageview3.image=uigraphicsgetimagefromcurrentImagecontext (); 98//Close Context uigraphicsendimagecontext (); NSLog (@ "Picture merge complete---%@", [Nsthread Curren TThread]); 101}); 102//103}); 104}105 106//Encapsulate a method, pass in a URL parameter, return a picture downloaded on the network 107-(UIImage *) Imagewithurl :(NSString *) urlStr108 {109 Nsurl *url=[nsurl urlwithstring:urlstr];110 nsdata *data=[nsdata datawithcontentsofurl : url];111 UIImage *image=[uiimage imagewithdata:data];112 return image;113}114 @end

Print view (open two sub-threads at the same time, download pictures separately):

2. Additional Information

There are 1 types of requirements:

First: Perform 2 time-consuming operations asynchronously, respectively

Second: Wait for 2 asynchronous operations to complete, then return to the main thread to perform the operation

If you want to implement these requirements quickly and efficiently, consider using queue groups

dispatch_group_t group = Dispatch_group_create ();

Dispatch_group_async (Group, Dispatch_get_global_queue (Dispatch_queue_priority_default, 0), ^{

Perform 1 time-consuming asynchronous operations

});

Dispatch_group_async (Group, Dispatch_get_global_queue (Dispatch_queue_priority_default, 0), ^{

Perform 1 time-consuming asynchronous operations

});

Dispatch_group_notify (Group, Dispatch_get_main_queue (), ^{

When the previous asynchronous operation is complete, return to the main thread ...

});

The common usage of iOS development multithreaded article 08-GCD

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

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.