One, what is GCD
GCD is one of the techniques for performing tasks asynchronously, typically implementing the code for thread management described in the application at the system level. Developers only need to define the tasks they want to perform and append them to the appropriate dispatch queue, GCD can generate the necessary threads and plan to perform the task. Because thread managers are implemented as part of a system, they can be managed uniformly and can perform tasks that are more efficient than previous threads.
That is to say, GCD uses our incredibly simple narrative method to achieve extremely complex multithreaded programming, which can be said to be an epoch-making technique. The following is an example of using the GCD source code, although slightly abstract, but also can feel the power of GCD
Dispatch_async (queue,^{ /* / long time processing such as AR with image recognition such as database access * / / * long processing ends the main thread processing result * /DISPATCH_ASYCN (Dispatch_get_main_queue (), ^{ /* Update UI interface on main thread */ } ) ;
Above is the execution of long processing in the background thread, processing ends using the main thread processing results
Dispatch_async (queue,^{});
This is a single line of code that allows processing to be performed in a background thread
DISPATCH_ASYCN (Dispatch_get_main_queue (), ^{ /* Update UI interface on the main thread */ });
This way, only this line of code allows processing to be executed in the main thread, and GCD uses block, further simplifying the application's code
Before importing GCD, the Cocoa Framework provides performselectorinbackground for the NSObject class: Withobject instance method and Performselectoronmainthread instance method are simple multithreaded programming techniques. For example, you can use the Performselector system method to implement the previous GCD source code to see
//executing a background thread-(void) launchthreadbynsobject_performselectorinbackground_withobject{[self performselectorinbackground: @selector (doWork) Withobject:nil]; }//Background Threading Methods-(void) dowork{NSAutoreleasePool*pool=[[NSAutoreleasePool alloc]init]; /*long-time processing*/ //process end, main thread update[Self performselectoronmainthread: @selector (donework) Withobject:nil Waituntildone:no]; [Pool drain]; }//main thread processing method-(void) donework{//update the UI interface and more}