Brief introduction
Nsoperationqueue (Operation queue) is a cocoa abstraction of the queue model provided by GCD and is a set of Objective-c APIs
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 choice for developers
Queues and operations
is object-oriented threading technology
Provides some features that are not easily implemented in GCD, such as limiting the maximum number of concurrent numbers, and the dependencies between operations
Nsoperationqueue has two different types of queues: The home row and the custom queue
The primary queue runs on the main thread
Custom queues are executed in the background
The task that the queue handles is a subclass of Nsoperation
Nsinvocationoperation
Nsblockoperation
defining queues
Self.myqueue = [[Nsoperationqueue alloc] init];
Method of Operation Invocation
-(void) Operationaction: (ID) obj
{
NSLog (@ "%@-obj:%@", [Nsthread CurrentThread], obj);
}
Define actions and add to queues
Nsinvocationoperation *op = [[Nsinvocationoperation alloc] initwithtarget:self selector: @selector (operationaction:) object:@ (i)];
[Self.myqueue Addoperation:op];
Summary: You need to prepare a scheduled method and be able to receive a parameter
Define actions and add to queues
Nsblockoperation *op = [Nsblockoperation blockoperationwithblock:^{
[Self operationaction:@ "Block operation"];
}];
Add an action to a queue
[Self.myqueue Addoperation:op];
Summary: nsblockoperation more flexible than nsinvocationoperation
Nsblockoperation *OP1 = [Nsblockoperation blockoperationwithblock:^{NSLog (@"%@-Download Image", [Nsthread CurrentThread]);}]; Nsblockoperation*OP2 = [Nsblockoperation blockoperationwithblock:^{NSLog (@"%@-Add picture filter", [Nsthread CurrentThread]);}]; Nsblockoperation*OP3 = [Nsblockoperation blockoperationwithblock:^{NSLog (@"%@-Update UI", [Nsthread CurrentThread]);}]; [Op2 ADDDEPENDENCY:OP1]; [Op3 ADDDEPENDENCY:OP2]; [Self.myqueue ADDOPERATION:OP1]; [Self.myqueue ADDOPERATION:OP2]; [[Nsoperationqueue Mainqueue] addoperation:op3];
Tip: You can use Adddependency to specify the dependencies between operations (execution sequence)
Note: Do not appear circular dependent!
Set the number of concurrent threads concurrently
Setting the number of concurrent threads can effectively reduce CPU and memory overhead
[Self.myqueue setmaxconcurrentoperationcount:2];
for (int i = 0; i < ++i) {
Nsblockoperation *op = [Nsblockoperation blockoperationwithblock:^{
[Self operationaction:@ (i)];//Why doesn't it cause a circular reference?
because the management of blocks and the creation and destruction of threads are the responsibility of the queue, the direct use of self is not related, and cannot be used __weak
}];
[Self.myqueue Addoperation:op];
}
IOS multithreaded-nsoperation/nsoperationqueue