IOS开发知识点

swift中 NSOperation 的使用

2021-02-11  本文已影响0人  90后的晨仔

参考文献一
参考文献二
苹果官方文档
总结来源于以上三个文献,希望大家可以去读读原作者的理解。这里主要是自己学习记录一下。

一、NSOperation的特点:
二、NSOperation的使用步骤:
三、NSBlockOperation使用

在官方文档有关同步和异步的问题有特别说明官方文档,默认情况下是不会开启新线程,也就是说默认是同步。

let operation = BlockOperation {
            
    print("任务---\(Thread.current)")
}
operation.start()
任务---<NSThread: 0x600003494300>{number = 1, name = main}

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()

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)")
}

控制最大并发数,默认为并发执行,若设置为1的时候为串行执行。大于1时,进行并发执行,当然这个值不应超过系统限制,即使自己设置一个很大的值,系统也会自动调整

通过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)
上一篇 下一篇

猜你喜欢

热点阅读