Nsoperation
Nsoperation encapsulates some of the GCD's operations and implements multithreading in a more object-oriented way
To create a multithreaded procedure
- 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
Nsoperation is an abstract class and does not have the ability to encapsulate operations, it must use its subclasses
- Nsinvocationoperation
- Nsblockoperation
- Customizing subclass Inheritance Nsoperation, implementing the corresponding method internally
Nsoperation can invoke the Start method to perform a task, but it is performed synchronously by default
If you add nsoperation to the Nsoperationqueue (action queue), the system automatically executes the operations in Nsoperation asynchronously
Nsinvocationoperation creating multithreading does not use queues
NSInvocationOperation *operation1 = [[NSInvocationOperation alloc] initWithTarget:selfselector:@selector(run) object:nil];//启动一个线程对象,默认调用run方法[operation1 start];//线程启动,没有这一句,线程不会启动//默认情况下,调用了start方法后并不会开一条新线程去执行操作,而是在当前线程同步执行操作//只有将NSOperation放到一个NSOperationQueue中,才会异步执行操作
Using queues
//创建一个队列对象 NSInvocationOperation *operation1 = [[NSInvocationOperation alloc] initWithTarget:self selector:@selector(run) object:nil];//创建一个操作[queue addOperation:operation1];//把操作加到队列中,自动开启一个新线程执行[queue addOperationWithBlock:^{ NSLog(@"1----%@-----", [NSThread currentThread]); }];//在队列中又添加一个操作
Nsblockoperation Creating multithreading
NSBlockOperation *operation2 = [NSBlockOperation blockOperationWithBlock:^{ NSLog(@"1----%@-----", [NSThread currentThread]); }];//第一个操作,不会新开一个线程线程[operation2 addExecutionBlock:^{ NSLog(@"2-----%@-----", [NSThread currentThread]); }];//添加操作,第二个操作,会开启一个线程[operation2 start];//启动线程//只要NSBlockOperation封装的操作数 > 1,就会异步执行操作
Using Queues to create multithreading
NSBlockOperation *operation2 = [NSBlockOperation blockOperationWithBlock:^{ NSLog(@"1----%@-----", [NSThread currentThread]);}];[operation2 addExecutionBlock:^{ NSLog(@"2-----%@-----", [NSThread currentThread]);}]; [queue addOperation:operation2];
Other operations of the thread set priority
设置NSOperation在queue中的优先级,可以改变操作的执行优先级- (NSOperationQueuePriority)queuePriority;- (void)setQueuePriority:(NSOperationQueuePriority)p
Operation Dependent
[operationB addDependency:operationA]; // 操作B依赖于操作A,必须A完成,才能执行B
Operation Monitoring
//可以监听一个操作的执行完毕- (void (^)(void))completionBlock;- (void)setCompletionBlock:(void (^)(void))block;
//opoeration操作完成后想要做什么事 operation.completionBlock = ^{ NSLog(@"NSBlockOperation------上衣脱完了,脱裤子---%@", [NSThread currentThread]); };
iOS Development-Multithreading uses nsoperation to create threads (use more)