swift中 NSOperation 的使用
2021-02-11 本文已影响0人
90后的晨仔
参考文献一
参考文献二
苹果官方文档
总结来源于以上三个文献,希望大家可以去读读原作者的理解。这里主要是自己学习记录一下。
一、NSOperation的特点:
- 1.基于GCD封装的抽象类。
- 2.如果不使用
NSOperationQueue
单独使用为同步操作,不会开启线程。异步执行需要配合NSOperationQueue
使用。 - 3.有两个子类分别为:
NSInvocationOperation
和NSBlockOperation
。 - 4.可以添加依赖控制所需要执行的任务。
- 5.可以通过
maxConcurrentOperationCount
控制并发数量。 - 6.NSOperation支持KVO(Key-Value Observing),可以方便的监听任务的状态(完成、执行中、取消等等状态)
- GCD是按FIFO顺序来执行的,而NSOperation能够方便地通过依赖关系设置操作执行顺序,可以控制任务在特定的任务执行完后才执行。
- 8.swfit 中
NSOperation
和NSOperationQueue
都去掉了前缀NS
,直接叫Operation
和OperationQueue
。 - 苹果认为
NSInvocationOperation
不是类型安全或者不是 ARC 安全的,在 Swift中 取消了与之相关的 API。
- 苹果认为
二、NSOperation的使用步骤:
- 创建任务:先将需要执行的任务封装到一个 NSOperation 对象中。
- 创建队列:创建一个 NSOperationQueue 对象。
- 任务加入队列:然后将 NSOperation 对象添加到 NSOperationQueue 对象中。
三、NSBlockOperation使用
- 1.没有使用
NSOperationQueue
的前提下,默认是同步,并且不会开启新的线程。
在官方文档有关同步和异步的问题有特别说明官方文档,默认情况下是不会开启新线程,也就是说默认是同步。
-
例子:
let operation = BlockOperation {
print("任务---\(Thread.current)")
}
operation.start()
-
控制台输出:
任务---<NSThread: 0x600003494300>{number = 1, name = main}
- 2.通过
addExecutionBlock
添加的任务会在其他线程中并发执行。
let operation = BlockOperation {
print("任务---\(Thread.current)")
}
operation.addExecutionBlock {
print("任务2---\(Thread.current)")
}
operation.addExecutionBlock {
print("任务3---\(Thread.current)")
}
operation.start()
四、NSOperationQueue
只有两种队列:
主队列
和其他队列
。其他队列可以用来实现串行和并发。
-
如下:
//创建主队列
let mainQueue = OperationQueue.main
//创建其他队列
let otherQueue = OperationQueue()
-
1.任务添加的方式有两种方法
- 把操作对象添加到队列
let queue = OperationQueue()
let operation1 = BlockOperation {
print("任务1---\(Thread.current)")
}
let operation2 = BlockOperation {
print("任务2---\(Thread.current)")
}
//把操作对象添加到队列
queue.addOperation(operation1)
queue.addOperation(operation2)
- 直接在队列中添加操作任务
let queue = OperationQueue()
queue.addOperation {
print("任务---\(Thread.current)")
}
-
2. maxConcurrentOperationCount
控制最大并发数,默认为并发执行,若设置为1的时候为串行执行。大于1时,进行并发执行,当然这个值不应超过系统限制,即使自己设置一个很大的值,系统也会自动调整
-
3.NSOperation 操作依赖
通过
addDependency
方法添加依赖,当然对应的也有移除依赖的方法removeDependency
。
let queue = OperationQueue()
let op1 = BlockOperation {
print("任务1---\(Thread.current)")
}
let op2 = BlockOperation {
print("任务2---\(Thread.current)")
}
let op3 = BlockOperation {
print("任务3---\(Thread.current)")
}
//op3依赖于op1,则先完成op1,再完成op3
op3.addDependency(op1)
//op1依赖于op2,则先完成op2,再完成op1
op1.addDependency(op2)
//最终的依赖关系就是,op2->op1->op3
queue.addOperation(op1)
queue.addOperation(op2)
queue.addOperation(op3)
-
4.其他方法
- isReady
- isExecuting
- isCancelled
- isConcurrent
- isAsynchronous
- isConcurrent