We generally use the following dispatch method:
Explanation: The first sentence is asynchronous execution, the second sentence is deferred asynchronous execution, the third sentence is to run the background, and then update the UI
The dispatch_get_main_queue represents the application main thread execution, and the UI can be updated internally (without blocking the main thread)
The Dispatch_get_global_queue representative runs in the background of the system, not necessarily with the UI on the same thread, cannot update the UI, and is suitable for processing of network processing and core data.
Modifying variables outside the block
Accessing Variables
By default, external variables that are accessed in the block are assigned (assign) past, meaning that the write operation does not take effect on the original variable. But you can add __block to make the write operation work, the sample code is as follows:
__block int a = 0;
void (^foo) (void) = ^{
A = 1;
}
Foo ();
Here, the value of a is modified to 1
Accessing Objects
If you are accessing objects such as self within a block of code, it is recommended to use a weak pointer reference before using it in a code block (closure).
In OC
__weak __typeof (&*self) ws = Self;
In Swift, declare within the closure
[unowned Self]
Other than that
GCD also has some advanced usage, such as having 2 threads in the background executing in parallel, and then summarizing the execution results after 2 threads have finished. This can be achieved with Dispatch_group, Dispatch_group_async, and Dispatch_group_notify, as shown in the following example:
dispatch_group_t group = Dispatch_group_create ();
Dispatch_group_async (Group, Dispatch_get_global_queue (0,0), ^{
Parallel execution of Line Cheng
});
Dispatch_group_async (Group, Dispatch_get_global_queue (0,0), ^{
Thread Two for parallel execution
});
Dispatch_group_notify (Group, Dispatch_get_global_queue (0,0), ^{
Summary results
});
REF:
Http://stackoverflow.com/questions/17351810/difference-between-dispatch-get-main-queue-and-dispatch-get-global-queue
https://developer.apple.com/library/ios/documentation/Performance/Reference/GCD_libdispatch_Ref/index.html#// Apple_ref/c/func/dispatch_main
http://blog.csdn.net/ericsuper/article/details/6998856
http://blog.csdn.net/marujunyy/article/details/8554920
Common dispatch methods for gcd--in Swift