1. Dispatch method provided by the system
to facilitate the use of GCD, Apple provides a number of ways for us to put blocks on the main thread or daemon, or postpone execution.
Background execution: dispatch_async (Dispatch_get_global_queue (dispatch_queue_priority_default, 0), ^{ //something }); Main thread Execution Dispatch_async (Dispatch_get_main_queue (), ^{ //something }); Once executed static dispatch_once_t once; Dispatch_once (&once, ^{ //something }); Delay 2 seconds to execute double delayinseconds = 2.0; dispatch_time_t poptime = Dispatch_time (Dispatch_time_now, delayinseconds * nsec_per_sec); Dispatch_after (Poptime, Dispatch_get_main_queue (), ^{ //something });
Dipatch_queue_t can also be defined by itself and implemented by the Dispatch_queue_creat method, for example:
dispatch_queue_t my_queue = dispatch_queue_create ("Myqueue", NULL); Dispatch_async (My_queue, ^{ //something }); Dispatch_release (My_queue);
In addition, GCD also has some advanced usage, for example, to let the background two threads execute in parallel, and then wait for two threads to end, after the summary execution result:
dispatch_group_t group = Dispatch_group_create (); Dispatch_group_async (Group, Dispatch_get_global_queue (Dispatch_queue_priority_default, 0), ^{ //thread for parallel execution 1 }); Dispatch_group_async (Group, Dispatch_get_global_queue (Dispatch_queue_priority_default, 0), ^{ //thread for parallel execution 2 }); Dispatch_group_notify (Group, Dispatch_get_global_queue (Dispatch_queue_priority_default, 0), ^{ //Aggregated results });
2. Running in the backgroundblock allows the program to run in the background for a long time, before the time should be pressed home button, up to only 5 seconds of background uptime, But the app can call Uiapllication's Beginbackgroundtaskwithexoirationhandler method, allowing the application to run in the background for up to 10 minutes, which can be done to clean up the cache, send statistics, and so on.
AppDelegate.h file @property (nonatomic, assign) Uibackgroundtaskidentifier Backgroundupdatetask;
appdelegate.m-(void) Applicationdidenterbackground: (uiapplication *) application { [self Beginbackgrooundupdatetask]; Add the code you need to run long-term [self endbackgrooundupdatetask];} -(void) beginbackgrooundupdatetask{ self.backbackgroundupdatetask = [[UIApplication sharedapplication] beginbackgroundtaskwithexpirationhandler:^{ [self endbackgrooundupdatetask];} ];} -(void) endbackgrooundupdatetask{ [[UIApplication sharedapplication] Endbackgroundtask: Self.backbackgroundupdatetask]; Self.backbackgroundupdatetask = Uibackgroundtaskinvalid;}
Xiao Fat said things--------GCD notes