相对于GCD。NSOperation更加灵活,能够自如地操作生命周期。
NSOperation是一个抽象的类,在使用时,使用的是他的两个子类NSInvocationOperation和
基本实现
NSInvocationOperation:target形式
- (void)baseUseDemo {
NSInvocationOperation *op = [[NSInvocationOperation alloc] initWithTarget:self selector:@selector(doSomething) object:nil];
[NSOperationQueue.mainQueue addOperation:op];
}
- (void)doSomething {
NSLog(@"hello Operation");
}
NSBlockOperation:block形式
- (void)baseUseDemo {
NSBlockOperation *blockOp = [[NSBlockOperation alloc] init];
//添加执行代码块
[blockOp addExecutionBlock:^{
NSLog(@"This is BlockOperation!");
}];
//设置监听
blockOp.completionBlock = ^{
NSLog(@"Completion");
};
//添加到队列
NSOperationQueue *queue = [[NSOperationQueue alloc] init];
[queue addOperation:blockOp];
}
优先级
blockOp.qualityOfService = NSQualityOfServiceUserInteractive;
typedef NS_ENUM(NSInteger, NSQualityOfService) {
NSQualityOfServiceUserInteractive = 0x21,
NSQualityOfServiceUserInitiated = 0x19,
NSQualityOfServiceUtility = 0x11,
NSQualityOfServiceBackground = 0x09,
NSQualityOfServiceDefault = -1
} API_AVAILABLE(macos(10.10), ios(8.0), watchos(2.0), tvos(9.0));
UserInteractive优先级最高,NSQualityOfServiceBackground优先级最低。
设置并发数
queue.maxConcurrentOperationCount = 2;
设置依赖关系
- (void)dependencyDemo {
NSBlockOperation *op1 = [NSBlockOperation blockOperationWithBlock:^{
[NSThread sleepForTimeInterval:0.5];
NSLog(@"任务1");
}];
NSBlockOperation *op2 = [NSBlockOperation blockOperationWithBlock:^{
[NSThread sleepForTimeInterval:0.5];
NSLog(@"任务2");
}];
NSBlockOperation *op3 = [NSBlockOperation blockOperationWithBlock:^{
[NSThread sleepForTimeInterval:0.5];
NSLog(@"任务3");
}];
[op2 addDependency:op1];
[op3 addDependency:op2];
NSOperationQueue *queue = [[NSOperationQueue alloc] init];
[queue addOperations:@[op1, op2, op3] waitUntilFinished:YES];
}
挂起
[queue setSuspended:YES];
注意:suspended不能挂起已经被执行的任务。
[queue cancelAllOperations];
干掉所有任务。下次得重新添加任务