多线程下的NSOperation和NSOperationQueue的使用
NSOperation和NSOperationQueue的介绍:
NSOperation是Cocoa中的一个抽象类,用来封装单个任务和代码执行一项操作,由于是抽象类,所以不能直接实例化使用,必须定义子类继承该抽象类来实现,比较常用的NSOperation的子类有NSInvocationOperation,另外,也可以自己继承NSOperation来实现线程的操作。
NSOperationQueue,它相当于一个线程队列或者可以叫做线程池。可以顺序执行队列中的操作,也可以设置队列中操作的优先级。
将上述这两个类配合起来使用,就可以实现多线程编程了。
NSOperation的使用:
NSOperation的两个子类的设置事件的方法:
NSInvocationOperation *operation1 = [[NSInvocationOperation alloc] initWithTarget:self selector:@selector(selector:) object:nil];
NSBlockOperation *blockOperation = [[NSBlockOperation alloc] init];
[blockOperation addExecutionBlock:^{
NSLog(@"1st the thread is %@", [NSThread currentThread]);
}];
[operation1 start];
第一个是使用NSInvocationOperation来设置事件。
第二个是使用NSBlockOperation来设置事件,事件在代码开中设置。
第三个是单独开启某个NSOperation子类的事件的方法。
NSOperationQueue的使用:
NSOperationQueue *queue = [[NSOperationQueue alloc] init];
[queue addOperation:operation1];
[operation1 addDependency:operation2];<span style="white-space:pre"> </span>
<span style="color: rgb(52, 52, 52); font-family: 'Source Code Pro', monospace; font-size: 16.2000007629395px; white-space: pre-wrap;">[NSOperationQueue mainQueue]</span>
第一个方法:创建和初始化队列
第二个方法: 添加事件,如果事件添加了,那么程序就直接运行了
第三个方法:事件的先后顺序设置
第四个方法:获取主队列
使用上述方法实例
@implementation NSOperationController
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view.
[self.view setBackgroundColor:[UIColor whiteColor]];
// [self invocationOperation1];
}
#pragma mark detail method
-(void) invocationOperation1{
// 使用NSInvocationOperation类来设置事件
NSInvocationOperation *operation1 = [[NSInvocationOperation alloc] initWithTarget:self selector:@selector(logTheOperation:) object:@"this is the frist invovationOpration"];
NSInvocationOperation *operation2 = [[NSInvocationOperation alloc] initWithTarget:self selector:@selector(logTheOperation:) object:@"this is the second invocationOperation"];
// 使用NSBlockOperation来设置事件,并且添加事件
NSBlockOperation *blockOperation = [[NSBlockOperation alloc] init];
[blockOperation addExecutionBlock:^{
NSLog(@"1st the thread is %@", [NSThread currentThread]);
}];
[blockOperation addExecutionBlock:^{
NSLog(@"2st the thread is %@", [NSThread currentThread]);
}];
[blockOperation addExecutionBlock:^{
NSLog(@"3st the thread is %@", [NSThread currentThread]);
}];
// 在这里我们还可以设置事件的先后顺序,这样一设置,运行顺序应该是blockOperation->operation1->operation2
[operation1 addDependency:operation2];
[blockOperation addDependency:operation2];
// 初始化一个队列
NSOperationQueue *queue = [[NSOperationQueue alloc] init];
// 将事件添加到队列中
[queue addOperation:operation1];
[queue addOperation:operation2];
[queue addOperation:blockOperation];
// 用另一种方法来存放事件
// [operation1 start];
// [operation2 start];
// [blockOperation start];
}
-(void) logTheOperation:(NSString *)log
{
NSLog(@"%@the thread is %@",log, [NSThread currentThread]);
}
@end