>>>>>>>> Multithreading in iOS provides the following methods:
1. performSelector (InBackground or MainThread)
This method is convenient, but the problem is that parameter passing only supports one object (passing multiple parameters, I package them in a NSDictionary)
2. NSOperationQueue
This method is a little complicated and provides the encapsulation of each task (NSOperation ). After NSOperation can be inherited, write some code for Synchronous execution in the main function, and put it in a Queue. Queue automatically manages Operation execution and scheduling (outside the UI thread ). For the code to be executed asynchronously, several NSOperation functions need to be reloaded to work properly (tell Queue about the progress and execution of this task ).
3. NSThread
I have not studied this method, but intuition is complicated.
4. GCD
Switching between the UI thread and other threads is very convenient. I like to use it with NSOperationQueue. This article focuses on this method.
5, pthread
>>>>>>>> GCD usage
Click a button to display loading, download an image in the background, and put the downloaded image in UIImageView for example.
// Display loading
Self. indicator. hidden = NO;
[Self. indicator startAnimating];
// Enter the asynchronous thread
Dispatch_async (dispatch_get_global_queue (DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^ {
// Download images Asynchronously
NSURL * url = [NSURL URLWithString: @ "http: // anImageUrl"];
NSData * data = [NSData dataWithContentsOfURL: url];
// Enter the main thread after the network request
Dispatch_async (dispatch_get_main_queue (), ^ {
// Disable loading
[Self. indicator stopAnimating];
Self. indicator. hidden = YES;
If (data) {// display the image
Self. imageView. image = [UIImage imageWithData: data];
}
});
});
In this way, GCD can be used to put the code about a task together. Instead of spreading code around like using the first method.
>>>>>>> Method of delaying task execution using GCD
// 2 seconds delayed execution:
Double delayInSeconds = 2.0;
Dispatch_time_t popTime = dispatch_time (DISPATCH_TIME_NOW, delayInSeconds * NSEC_PER_SEC );
Dispatch_after (popTime, dispatch_get_main_queue (), ^ (void ){
// Code to be executed on the main queue after delay
});
>>>>>>> Create your own Queue
Dispatch_queue_t custom_queue = dispatch_queue_create ("mmqueue", NULL );
Dispatch_async (custom_queue, ^ {
// Doing something in custom_queue
});
Dispatch_release (custom_queue );
>>>>>>> Use GCD to run multiple threads concurrently and wait until all threads end before executing other tasks.
Dispatch_group_t group = dispatch_group_create ();
Dispatch_group_async (group, dispatch_get_global_queue (0, 0), ^ {
// Thread 1 for Parallel Execution
});
Dispatch_group_async (group, dispatch_get_global_queue (0, 0), ^ {
// Thread 2 for Parallel Execution
});
Dispatch_group_notify (group, dispatch_get_global_queue (0, 0), ^ {
// Summary Result
});