Overview
Nsoperation is a GCD-based encapsulation is more object-oriented, in use is also the concept of tasks and queues, respectively, corresponding to two classes nsoperation, Nsoperationqueue
Nsoperation and Nsoperationqueue steps to implement multithreading
- The actions that need to be performed are now encapsulated 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 one thread to execute
Nsoperation
Nsoperation is an abstract class that needs to use its subclasses when used. Nsoperation A total of two subclasses.
- Nsinvocationoperation
- Nsblockoperation
开发中一般NSOperation子类通常与NSOperationQueue一起使用才能更好的开辟线程。
Nsoperationqueue
Nsoperation can invoke the Start method class to perform tasks, but it is synchronized by default. If you add nsoperation to Nsoperationqueue, the system automatically executes the operations in nsoperation asynchronously.
Nsoperationqueue uses only two types, the home row and the non-home row (including serial, concurrency). Two ways to get a queue:
[NSOperationQueue mainQueue]; // 主队类[[NSOperationQueue alloc] init]; // 非主队列
All tasks added to the home row are executed in the main thread. Tasks that are not a home column are automatically added to the child threads for execution. Concurrency is determined by the maxconcurrentoperationcount of the queue with the serial.
#import "ViewController.h"@interface ViewController ()@end@implementation ViewController- (void)viewDidLoad { [super viewDidLoad]; NSOperationQueue *queue = [[NSOperationQueue alloc] init]; NSInvocationOperation *operation = [[NSInvocationOperation alloc] initWithTarget:self selector:@selector(task) object:nil]; [queue addOperation:operation];// [operation start]; NSBlockOperation *blockOperation = [NSBlockOperation blockOperationWithBlock:^{ NSLog(@"------------%@", [NSThread currentThread]); }]; // 添加额外的任务才会在子线程执行 [blockOperation addExecutionBlock:^{ NSLog(@"------------%@", [NSThread currentThread]); }]; [queue addOperation:blockOperation]; // [blockOperation start]; }- (void)task{ NSLog(@"------------%@", [NSThread currentThread]);}
Once the nsoperation is added to the nsoperationqueue, it is not necessary to call Nsoperation's Start method, which automatically calls back the start of nsoperation.
In development, you can also customize the way nsoperation, overriding the main method to encapsulate the task. This is recommended if the task is more code-based and needs to be used in many parts of the program.
#import "FMOperation.h"@implementation FMOperation- (void)main{ // 封装任务 }@end
iOS Development Series-nsoperation