也许这个问题比我看起来更普遍,但我想确保我展示了我的完整背景,以防出现这个问题的原因。
class Singleton: NSObject {
static let sharedInstance = Singleton()
@objc dynamic var aProperty = false
func updateDoesntWork() {
aProperty = !aProperty
}
func updateDoesWork() {
Singleton.sharedInstance.aProperty = !aProperty
}
}
Singleton.sharedInstance.addObserver(self, forKeyPath: #keyPath(Singleton.aProperty), options: [.new], context: nil)
observeValue()
方法:override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {
NSLog("observeValue(forKeyPath: \(String(describing:keyPath)), of: \(String(describing:object)), change: \(String(describing:change)), context:\(String(describing:context)))")
}
现在,如果我打电话给Singleton.sharedInstance.updateDoesntWork()
,我没有得到aProperty
变化的日志条目。该属性已更改(我在调试器中验证了这一点),只是没有发送通知。
然而,如果我调用Singleton.sharedInstance.updateDoesWork()
,一切都按照我的预期工作 - 当然,属性也会改变,但最重要的是,这次观察者会收到更改通知(打印日志条目)。
我觉得我应该需要完整的Singleton.sharedInstance.aProperty
而不仅仅是aProperty
让KVO工作是没有意义的。我错过了什么?
我假设您对单例使用“var”有困难。您可以考虑使用以下代码段来创建单例并初始化一些值,包括单例专用的观察值:
class Singleton: NSObject {
static private var sharedInstanceObserver : NSKeyValueObservation!
static let sharedInstance: Singleton = {
let sInstance = Singleton()
sharedInstanceObserver = sInstance.observe(\Singleton.aProperty, options: .new) { st, value in
print(st, value)
}
return sInstance
}()
@objc dynamic var aProperty = false
func updateDoesntWork() {
aProperty = !aProperty
}
func updateDoesWork() {
Singleton.sharedInstance.aProperty = !aProperty
}
}