// NSOperation 的三种方式,
/**
* 1.NSInvocationOperation
* 注意:
1. 默认情况下,调用了start方法后并不会开一条新线程去执行操作,而是在当前线程同步执行操作
2. 只有将 NSOperation 放到一个 NSOperationQueue中,才会异步执行操作
*/
- (void)InvocationOperation {
// 1.创建操作对象,封装要执行的任务
NSInvocationOperation *operation = [[NSInvocationOperation alloc] initWithTarget:self selector:@selector(download) object:nil];
// 2.执行操作(默认情况下,如果操作没有放到queue中,都是同步执行)
[operation start];
}
- (void)download {
NSLog(@"---download---%@",[NSThread currentThread]);
}
/**
* 2.NSBlockOperation
* 注意:
只要 NSBlockOperation 封装的操作数 > 1,就会异步执行操作
*/
- (void)blockOperation {
// 1.封装操作
NSBlockOperation *operation = [NSBlockOperation blockOperationWithBlock:^{
NSLog(@"---download1---%@",[NSThread currentThread]); 在主线程中操作
}];
// 不用加入queue中也可以开启线程,这个取决于任务的个数,
[operation addExecutionBlock:^{
NSLog(@"---download2---%@",[NSThread currentThread]);
}];
[operation addExecutionBlock:^{
NSLog(@"---download3---%@",[NSThread currentThread]);
}];
// 2.执行操作
[operation start];
}
PS:还可以监听:
- (void)operationListen {
NSBlockOperation *operation = [NSBlockOperation blockOperationWithBlock:^{
NSLog(@"NSBlockOperation---download---%@",[NSThread currentThread]);
}];
operation.completionBlock = ^{
// 下载完图片后想做事情
NSLog(@"NSBlockOperation---download图片完毕---%@",[NSThread currentThread]);
};
NSOperationQueue *queue = [[NSOperationQueue alloc] init];
[queue addOperation:operation];
}
上面两个方式可以跟 NSOperationQueue 一起使用 ,如果不放到 NSOperationQueue 里面的话,会在主线程运行
- (void)operationQueue {
// 1. 封装操作
NSInvocationOperation *operation1 = [[NSInvocationOperation alloc] initWithTarget:self selector:@selector(download) object:nil];
// 优先级
operation1.queuePriority = NSOperationQueuePriorityVeryHigh;
NSInvocationOperation *operation2 = [[NSInvocationOperation alloc] initWithTarget:self selector:@selector(run) object:nil];
NSBlockOperation *operation3 = [NSBlockOperation blockOperationWithBlock:^{
NSLog(@"NSBlockOperation---download1---%@",[NSThread currentThread]);
}];
[operation3 addExecutionBlock:^{
NSLog(@"NSBlockOperation---download2---%@",[NSThread currentThread]);
}];
// 2. 创建队列
*queue = [[NSOperationQueue alloc] init];
// 设置依赖 , 1执行完才执行2 *** 可以在不同queue中创建依赖关系 ***
[operation2 addDependency:operation1];
// 最大并发数,控制同一时间开的最多的线程数 5以内 2 ~ 3
// queue.maxConcurrentOperationCount = 2;
// 3. 添加操作到队列中(自动执行操作,自动开启线程)
[queue addOperation:operation1];
[queue addOperation:operation2];
[queue addOperation:operation3];
// 取消队列的所有操作
// [queue cancelAllOperations];
//
// // 暂停/恢复 no
// [queue setSuspended:YES];
}
- (void)download {
NSLog(@"---download---%@",[NSThread currentThread]);
}
- (void)run {
NSLog(@"---run---%@",[NSThread currentThread]);
}
第三种形式是自定义的,下一篇博客里面会写