Skip to content

Instantly share code, notes, and snippets.

@sgr-ksmt
Created March 8, 2017 15:10
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save sgr-ksmt/ed922da995491fd0fe0b35b7fccbccb3 to your computer and use it in GitHub Desktop.
Save sgr-ksmt/ed922da995491fd0fe0b35b7fccbccb3 to your computer and use it in GitHub Desktop.
class Baz: NSObject {
dynamic var value: String = ""
override class func automaticallyNotifiesObservers(forKey key: String) -> Bool {
if key == "value" {
return true
}
return super.automaticallyNotifiesObservers(forKey: key)
}
}
class Foo: NSObject {
var baz: Baz? {
willSet {
baz?.removeObserver(self, forKeyPath: "value")
}
didSet {
baz?.addObserver(self, forKeyPath: "value", options: [.new, .old], context: nil)
}
}
override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {
if keyPath == "value" {
print(keyPath as Any, object as Any)
}
}
deinit {
// baz?.removeObserver(self, forKeyPath: "value") ☆
baz = nil
}
}
do {
let f = Foo()
let baz = Baz()
f.baz = baz
baz.value = "!!!"
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment