Brief introduction
- Multithreading can also be achieved through the combination of nsoperation and Nsoperationqueue
- Tasks are typically encapsulated into Nsoperation objects, and objects are added to Nsoperationqueue to implement
Nsoperation
- Nsoperation is an abstract class that cannot be used to encapsulate operations directly, typically using its subclasses to encapsulate operations
-
If you do not add the Nsoperation object to the Nsoperationqueue, the operation will only be performed on the current thread, and you will need to start the operation manually
-
Subclass of Nsoperation
-
Nsinvocationoperation
//创建操作NSInvocationOperation *operation = [[NSInvocationOperation alloc] initWithTarget:self selector:@selector(run) object:nil];//开始执行操作[operation start];
-
Nsblockoperation (asynchronous execution when operand is greater than 1 o'clock)
//创建操作NSBlockOperation *operation = [NSBlockOperation blockOperationWithBlock:^{ //操作封装的任务代码}];//添加操作[operation addExecutionBlock:^{ //操作封装的任务代码}];//开始执行操作[operation start];
-
To customize a subclass
- Override-(void) Main method, which encapsulates the action to be performed in the method
- In the-(void) Main method, you need to set up an auto-free pool yourself (cause: an asynchronous operation that cannot access the main thread's auto-free pool)
- Check the status of the operation by checking the properties such as cancelled, and perform the corresponding operation
-
Callback when the set operation completes
//创建操作NSBlockOperation *operation1 = [NSBlockOperation blockOperationWithBlock:^{ //任务代码}];//设置回调operation.completionBlock = ^{ //操作完成时执行的代码};
Nsoperationqueue
Steps to implement multithreading
-
Create an action queue
NSOperationQueue *queue = [[NSOperationQueue alloc] init]
-
Adding operations to the queue
/**方法一*///创建操作NSInvocationOperation *operation1 = [[NSInvocationOperation alloc] initWithTarget:self selector:@selector(download) object:nil] //download为操作封装的任务方法NSBlockOperation *operation2 = [NSBlockOperation blockOperationWithBlock:^{ //任务代码}];//添加操作[queue addOperation:operation1];[queue addOperation:operation2];/**方法二*///添加操作[queue addOperationWithBlock:^{ //操作封装的任务}];
Operation Dependent
Communication between threads
Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.
iOS multithreading -03-nsoperation and Nsoperationqueue