如何将KVO通知与线程安全结合起来?

hga*_*ale 5 ios swift

如何将 KVO 通知与线程安全结合起来?我有一个类需要符合 KVO 标准,这就是我目前的做法:

class CustomOperation: Operation {
    private let stateQueue = DispatchQueue(label: "customOperation", attributes: .concurrent)
    private var _isExecuting = false
    
    override var isExecuting: Bool {
        get {
            return stateQueue.sync { _isExecuting }
        }
        set {
            stateQueue.async(flags: .barrier) {
                self._isExecuting = newValue
            }
        }
    }
    
    override func start() {
        willChangeValue(forKey: "isExecuting")
        isExecuting = true
        didChangeValue(forKey: "isExecuting")
    }
}
Run Code Online (Sandbox Code Playgroud)

我可以像这样在属性设置器内移动通知吗?

class CustomOperation: Operation {
    private let stateQueue = DispatchQueue(label: "customOperation", attributes: .concurrent)
    private var _isExecuting = false
    
    override var isExecuting: Bool {
        get {
            return stateQueue.sync { _isExecuting }
        }
        set {
            stateQueue.async(flags: .barrier) {
                self.willChangeValue(forKey: "isExecuting")
                self._isExecuting = newValue
                self.didChangeValue(forKey: "isExecuting")
            }
        }
    }
    
    override func start() {
        isExecuting = true
    }
}
Run Code Online (Sandbox Code Playgroud)

这两个示例是否正确地将 KVO 通知与线程安全结合起来?