我正在使用
NSKeyValueObservation
来观察WKWebView
的子类中的属性。
在iOS 11上它运行良好,但在iOS 10上deinit
时会崩溃。
控制台上打印的错误日志
*** Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: 'An instance 0x15209e600 of class Rakuemon.WebView was deallocated while key value observers were still registered with it. Current observation info: <NSKeyValueObservationInfo 0x170232da0> (
<NSKeyValueObservance 0x170259bf0: Observer: 0x17027d500, Key path: loading, Options: <New: NO, Old: NO, Prior: NO> Context: 0x0, Property: 0x170643ba0>
<NSKeyValueObservance 0x170643480: Observer: 0x170c72f80, Key path: estimatedProgress, Options: <New: YES, Old: NO, Prior: NO> Context: 0x0, Property: 0x170643330>
<NSKeyValueObservance 0x170642c70: Observer: 0x17086c0c0, Key path: title, Options: <New: YES, Old: NO, Prior: NO> Context: 0x0, Property: 0x1706437b0>
)'
代码
class WebView: WKWebView {
// MARK: - Properties
weak var delegate: WebViewDelegate?
// MARK: - Private properties
private var contentSizeObserver: NSKeyValueObservation?
private var loadingObserver: NSKeyValueObservation?
private var estimatedProgressObserver: NSKeyValueObservation?
private var titleObserver: NSKeyValueObservation?
// MARK: - Life cycle
override init(frame: CGRect, configuration: WKWebViewConfiguration) {
super.init(frame: frame, configuration: configuration)
setupObserver()
}
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
// MARK: - Private functions
private extension WebView {
func setupObserver() {
contentSizeObserver = scrollView.observe(\.contentSize, options: [.old, .new], changeHandler: { [unowned self] _, change in
guard let oldSize = change.oldValue, let newSize = change.newValue, oldSize != newSize else { return }
self.delegate?.webView?(self, didChangeSizeFrom: oldSize, to: newSize)
})
loadingObserver = observe(\.isLoading, changeHandler: { [unowned self] _, _ in
self.delegate?.webViewIsLoading?(self)
})
estimatedProgressObserver = observe(\.estimatedProgress, options: [.new], changeHandler: { [unowned self] _, change in
guard let newValue = change.newValue else { return }
self.delegate?.webView?(self, didChangeEstimatedProgress: newValue)
})
titleObserver = observe(\.title, options: [.new], changeHandler: { [unowned self] _, change in
guard let title = change.newValue else { return }
self.delegate?.webView?(self, didChangeTitle: title ?? "")
})
}
}
问题
我还找到了contentSizeObserver
,它观察了scrollView.contentSize
而不是self
的属性,但并没有导致崩溃。
那么,在iOS 10上通过NSKeyValueObservation
观察self
的属性的正确方法是什么?或者如何注销它?
deinit
中尝试了invalidate
和nil
两种方式,但没有成功... - mrfour