Wait for all Operations in queue to finish before performing task

前端 未结 6 1888
小鲜肉
小鲜肉 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:42

    A suitable solution is KVO

    First before the loop add the observer (assuming queue is the OperationQueue instance)

    queue.addObserver(self, forKeyPath:"operations", options:.new, context:nil)
    

    Then implement

    override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {
        if object as? OperationQueue == queue && keyPath == "operations" {
            if queue.operations.isEmpty {
                // Do something here when your queue has completed
                self.queue.removeObserver(self, forKeyPath:"operations")
            }
        } else {
            super.observeValue(forKeyPath: keyPath, of: object, change: change, context: context)
        }
    }
    

    Edit:

    In Swift 4 it's much easier

    Declare a property:

    var observation : NSKeyValueObservation?
    

    and create the observer

    observation = queue.observe(\.operationCount, options: [.new]) { [unowned self] (queue, change) in
        if change.newValue! == 0 {
            // Do something here when your queue has completed
            self.observation = nil
        }
    }
    

提交回复
热议问题