During iphone development, if you encounter loading big data or network communication problems, you need to complete these tasks in the background thread.
In addition to NSThread, the iphone also provides a GCD mechanism to help developers implement multi-threaded development.
Compared with NSThread, GCD is more efficient and easier to develop.
The basis of GCD is dispatch queue and block.
1. block can be simply understood as a task. The expression of block in the program is similar:
1 NSString * URL = @"......";
2
3 ^ {
4
5 UIImage * image = [UIImage imageWithURL: URL];
6
7 };
As shown in the preceding example, a block can reference data in an external scope. This is also the difference between block and common functions. block stores the context of the current execution.
2. dispatch queue is a FIFO task queue. Some blocks can be pushed into this queue, and the system will execute these blocks in order.
Dispatch_async ()
Three types of dispatch queue are provided by default in the system:
A. Main. If you want a block to be completed in the main thread, you can push it to the Main dispatch queue.
B. Concurrent. The system automatically creates three dispatch queue with different priorities. Block is not guaranteed to be executed in strict order.
C. Serial. Manual creation is required to ensure that the block is executed strictly in the push order.
The following is an example of Asynchronously loading network images:
1 UIImageView * imageView = [[UIImageView alloc] init];
2
3 dispatch_async (dispatch_get_global_queue (DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^ {
4
5 UIImage * image =; // network pull code
6
7 dispatch_async (dispatch_get_main_queue (), ^ {
8
9 imageView. image = image; // update the imageview in the main thread
10
11 });
12
13 });
From the code above, we can see that GCD's frontend and backend thread synchronization notification mechanism is much more elegant and convenient than NSThread.
For official apple documentation, see:
Http://developer.apple.com/library/ios/#documentation/Performance/Reference/GCD_libdispatch_Ref/Reference/reference.html
Other materials:
Http://www.bkjia.com/kf/201111/112639.html
Author: dongliqian