使用 - observeValueForKeyPath:ofObject:change:context: 在 Swift 3

Using - observeValueForKeyPath:ofObject:change:context: in Swift 3

我正在尝试将 Swift 2.2 项目转换为 Swift 3,但出现以下错误:

Method 'observeValue(forKeyPath:ofObject:change:context:)' with Objective-C selector 'observeValueForKeyPath:ofObject:change:context:' conflicts with method 'observeValue(forKeyPath:of:change:context:)' from superclass 'NSObject' with the same Objective-C selector" for the function call

我的函数签名是:

func observeValue(forKeyPath keyPath: String?, ofObject: Any?, change: [String : Any]?, context: UnsafeMutableRawPointer?)."

我已阅读 Swift 3 迁移指南网站上的建议:

"Workaround: Add an @objc(objectiveC:name:) attribute before the implementation of the optional requirement with the original Objective-C selector inside."

但我不清楚这实际上应该如何应用到源文件中,到目前为止我尝试的任何事情都没有成功。

谁能解释一下如何正确设置它?

只需开始输入 observeValueFor...Xcode 会建议您使用有效的自动完成功能。选择它,你就可以开始了。

你的函数应该看起来像这样:

override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) 

这就是(最终)在 Xcode 版本 8.0 (8A218a) 中使用 Swift 3.0 对我有用的东西:

@objc
override open func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {