尝试用现代的 swift 观察方式取代老式的 Objective-C 观察方式。但是我无法弄清楚关键路径。
//doesn't work
progress.observe(\.userInfo[ProgressUserInfoKey.fileCompletedCountKey], changeHandler: {_,_ in
})
Foundation/NSObject.swift:132: Fatal error: Could not extract a String from KeyPath \NSProgress.userInfo.<computed 0x00000001a5a1ecf0 (Optional<Any>)>
PS:您无法观察 fileCompletedCount,因为它是一个计算属性。
PS2:这不是一个重复的问题。请看图片。它正在被手动设置为动态属性。
旧代码:
import Cocoa
private var viewControllerObservationContext = 0
class ViewController: NSViewController {
private var progress: Progress = {
let progress = Progress()
progress.kind = .file
progress.fileTotalCount = 20
return progress
}()
override func viewDidLoad() {
super.viewDidLoad()
let filesCompletedKeyPath = "userInfo.NSProgressFileCompletedCountKey"
progress.addObserver(self, forKeyPath: filesCompletedKeyPath, options: .new, context: &viewControllerObservationContext)
DispatchQueue.main.asyncAfter(deadline: .now() + 1) {
self.progress.fileCompletedCount = 10
}
}
override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey: Any]?, context: UnsafeMutableRawPointer?) {
guard context == &viewControllerObservationContext else {
super.observeValue(forKeyPath: keyPath, of: object, change: change, context: context)
return
}
print(object)
print(keyPath)
}
deinit {
progress.removeObserver(self, forKeyPath: "userInfo.NSProgressFileCompletedCountKey")
}
}
观察
localizedDescription
以获取所有更新,包括 fileCompletedCount
和 fileTotalCount
let progress = Progress()
progress.observe(\.localizedDescription) { p, c in
print(p.fileTotalCount)
print(p.fileCompletedCount)
}
progress.fileCompletedCount = 10
progress.fileTotalCount = 11
nil
Optional(10)
Optional(11)
Optional(10)