Wait for all Operations in queue to finish before performing task

前端 未结 6 1908
小鲜肉
小鲜肉 2021-01-02 07:29

I have an Operation subclass and Operation queue with maxConcurrentOperationCount = 1.

This performs my operations in a sequential order that i add them which is goo

6条回答
  •  南笙
    南笙 (楼主)
    2021-01-02 07:52

    Code at the end of the queue refer to this link

    NSOperation and NSOperationQueue are great and useful Foundation framework tools for asynchronous tasks. One thing puzzled me though: How can I run code after all my queue operations finish? The simple answer is: use dependencies between operations in the queue (unique feature of NSOperation). It's just 5 lines of code solution.

    NSOperation dependency trick with Swift it is just easy to implement as this:

    extension Array where Element: NSOperation {
    /// Execute block after all operations from the array.
    func onFinish(block: () -> Void) {
        let doneOperation = NSBlockOperation(block: block)
        self.forEach { [unowned doneOperation] in doneOperation.addDependency($0) }
        NSOperationQueue().addOperation(doneOperation)
    }}
    

提交回复
热议问题