There are currently two sets of advanced synchronization APIs available in IOS and OS X for our use: Nsoperation and GCD. Where GCD is the underlying API based on C, and Nsoperation is the Objective-c API implemented by GCD.
1. When to use Nsoperationqueue instead of GCD
For example, you might have written code like this (to request network data):
1Dispatch_async (_queue, ^{2 3 //Request Data4NSData *data = [NSData datawithcontenturl:[nsurl urlwithstring:@"Http://domain.com/a.png"]];5 6Dispatch_async (Dispatch_get_main_queue (), ^{7 8 [self refreshviews:data];9 });Ten});
It can work normally, but there is a fatal problem: This task is unable to cancel dataWithContentURL: is the synchronous pull data, it will always block the thread until the completion of the request, if it is encountered a time-out situation, it will continue to occupy this thread during this time During this period, concurrent queues need to create new threads for other tasks, which can lead to problems such as performance degradation.
The Action queue (Operation queue) is a Cocoa abstraction of a queue model provided by GCD. GCD provides a lower level of control, while the operations queue implements some handy features on top of GCD, which are often the best and safest option for app developers. Nsoperationqueue has the following advantages relative to GCD:
- Provides useful features that are less easily duplicated in GCD.
- It is convenient to cancel the execution of a nsoperation
- The dependency of a task can be added more easily
- Provides the status of the task: Isexecuteing, isfinished.
noun: The above-mentioned "task", "action" represents the thing to be executed again in nsoperation.
Nsoperation and Nsoperationqueue steps to implement multithreading
Encapsulates the action that needs to be performed into a Nsoperation object
Then add the Nsoperation object to the Nsoperationqueue
The system will automatically remove the nsoperation from the Nsoperationqueue
Put the removed Nsoperation encapsulated operation into a new thread to execute
Nsoperation is an abstract class and does not have the ability to encapsulate operations, it must use its subclasses
There are 3 ways to use a nsoperation subclass
Nsinvocationoperation (by default, when the Start method is called, it does not open a new thread to perform the operation, but instead performs the operation synchronously in the current thread, and only puts nsoperation into a nsoperationqueue. Operation is performed asynchronously)
Nsblockoperation (operations are performed asynchronously, even if not added to Nsoperationqueue, as long as the nsblockoperation encapsulates the operand > 1)
Customizing subclass Inheritance Nsoperation, implementing the corresponding method internally
iOS multi-threading Nsoperation