Swift 4 KVO 操作观察期间致命错误

Swift 4 KVO fatal error during operations observing

我正在尝试在 Swift 4 中使用 KVO 观察 OperationQueue 操作计数,但在操作数组更改时出现致命错误。

操场上使用了以下代码:

import Foundation

class MyObjectToObserve:NSObject {
    @objc dynamic var queue = OperationQueue()
}

class MyObserver:NSObject {

    @objc var objectToObserve: MyObjectToObserve
    var observation: NSKeyValueObservation?

    init(object: MyObjectToObserve) {
        objectToObserve = object
        super.init()

        observation = observe(\.objectToObserve.queue.operations.count) { object, change in
            print("Observed")
        }
    }
}

let myObjectToObserve = MyObjectToObserve()
let myObserver = MyObserver(object: myObjectToObserve)

myObjectToObserve.queue.addOperation {
    print("First operation")
    }

这个错误:

Fatal error: Could not extract a String from KeyPath Swift.KeyPath<__lldb_expr_6.MyObserver, Swift.Int>: file /BuildRoot/Library/Caches/com.apple.xbs/Sources/swiftlang/swiftlang-900.0.74.1/src/swift/stdlib/public/SDK/Foundation/NSObject.swift, line 85

据我了解,问题是 OperationQueue 操作是 Swift 数组,KVO 无法使用它。我尝试使用带整数的数组而不是 OperationQueue 并得到相同的错误。 如何在Swift4中正确观察OperationQueue操作,或者有其他方法在OperationQueue完成所有任务时获得通知吗?

你不能观察数组的count 属性。 You cannot observe any property of an array:

NSArray objects are not observable, so this method raises an exception when invoked on an NSArray object.

OperationQueue有一个单独的operationCount属性供您观察。

    observation = observe(\.objectToObserve.queue.operationCount) { object, change in
        print("Observed")
    }