Basic iosGCD usage
Sleepy, sleep when it's over. You can understand the benefits of running it. I will not upload it here. You can run it yourself... Good night
# Import "ViewController. h"
@ Interface ViewController ()
{
UIImageView * _ view;
}
@ End
@ Implementation ViewController
-(Void) viewDidLoad {
[Super viewDidLoad];
// The main queue column is a queue associated with the main thread. The main queue column is a special queue provided by GCD. Tasks added to the main queue column are executed in the main thread. Note: No threads are created for adding tasks to the main queue, whether synchronous or asynchronous.
// Dispatch_get_main_queue (); Method for retrieving the main queue Column
// Enable the sub-thread to call the test method
[Self defined mselectorinbackground: @ selector (test) withObject: nil];
_ View = [[UIImageView alloc] init];
_ View. frame = CGRectMake (0, 0, self. view. bounds. size. width, 300 );
[Self. view addSubview: _ view];
}
-(Void) test
{
Dispatch_queue_t queue = dispatch_queue_create ("Concurrent Queue", DISPATCH_QUEUE_CONCURRENT );
Dispatch_async (queue, ^ {
NSLog (@ "222 curThread = % @", [NSThread currentThread]);
});
Dispatch_sync (queue, ^ {
NSLog (@ "333 cureThread = % @", [NSThread currentThread]);
});
}
// Click the screen to download an image from the network and display it on the interface.
-(Void) touchesBegan :( NSSet *) touches withEvent :( UIEvent *) event
{
// 1. Retrieve global queue
Dispatch_queue_t queue = dispatch_get_global_queue (DISPATCH_QUEUE_PRIORITY_DEFAULT, 0 );
// Add the image download task to the parallel queue
Dispatch_async (queue, ^ {
NSLog (@ "1111: curThread = % @", [NSThread currentThread]);
NSURL * url = [NSURL URLWithString: @ "http://h.hiphotos.baidu.com/image/pic/item/35a85edf8db1cb13966db40fde54564e92584ba2.jpg"];
NSData * data = [NSData dataWithContentsOfURL: url];
UIImage * image = [UIImage imageWithData: data];
// Use GCD to set the image to be displayed in the main thread.
// Benefit: Resources in the subthread can be directly used in the main thread. Easy to use and intuitive.
// The operation ui is executed in the main thread
Dispatch_async (dispatch_get_main_queue (), ^ {
_ View. image = image;
});
});
}
-(Void) test11
{
// Dispatch_queue_t queue = dispatch_get_global_queue (<# long identifier #>,< # unsigned long flags #>)
Dispatch_queue_t queue = dispatch_queue_create ("Concurrent Queue", DISPATCH_QUEUE_CONCURRENT );
Dispatch_async (queue, ^ {
// Perform time-consuming operations
Dispatch_async (dispatch_get_main_queue (), ^ {
// Operation UI
});
});
}
@ End