ios - 在枚举之前使用 '\' 观察实现
问题描述
最近我实现了一个进度视图来显示网页上的加载过程。我阅读了一个示例(https://gist.github.com/fxm90/50d6c73d07c4d9755981b9bb4c5ab931)并进行了修改。但是部分代码对我来说并不清楚,确切地说
\.estimatedProgress
这是相关的代码。
var webView: WKWebView!
// Progress view reflecting the current loading progress of the web view.
let progressView = UIProgressView(progressViewStyle: .default)
/// The observation object for the progress of the web view (we only receive notifications until it is deallocated).
private var estimatedProgressObserver: NSKeyValueObservation?
private func setupEstimatedProgressObserver() {
estimatedProgressObserver = webView.observe(\.estimatedProgress, options: [.new]) { [weak self] webView, _ in
self?.progressView.progress = Float(webView.estimatedProgress)
}
}
问题
- 为什么以及何时可以在枚举之前使用字符“\”?
- 是否不需要使用这种方式进行 deinit 或删除观察者?为什么?
解决方案
\<Type>.<path>
语法是Swift Key-Path 表达式(而不是枚举),本质上是对 some 路径的强类型引用Type
。当可以推断出类型时,您可以省略它,因此表达式变为\.path
(在您的示例中,完整表达式为\WKWebView.estimatedProgress
)。
上面的链接中有几个示例可以帮助您更好地理解这一点。
对于第二部分,观察只会持续只要estimatedProgressObserver
没有被释放(所以,只要有东西对它有很强的引用)。
推荐阅读
- opencv - 如何在段上应用ransac并绘制它们
- google-apps-script - How to increase i to next call?
- c# - Automapper 未映射子集合中的所有子实体
- c# - Calling a method from base class to class with same name as the method
- laravel - 尽管 APP_URL 正确,`url('')` 不会产生 https URL
- sql - Get records where all the corresponding columns of the same column is null
- excel - 第一次启动程序时,Excel VBA 代码中的引用不起作用
- c# - 为什么 WPF 窗口无法像在 Revit 2018 中那样在 Autodesk Revit 2019 中正确渲染
- django - Sending message from Celery task to Channels
- ios - 在 Google Analytics for Firebase 中显示自定义事件参数