Skip to content

Instantly share code, notes, and snippets.

@Ben-G
Created August 6, 2015 18:13
Show Gist options
  • Save Ben-G/31359abe4797a7182d96 to your computer and use it in GitHub Desktop.
Save Ben-G/31359abe4797a7182d96 to your computer and use it in GitHub Desktop.
import Foundation
class User: NSObject {
dynamic var name: String?
}
class Observer: NSObject {
var user: User
init(user: User) {
self.user = user
super.init()
self.user.addObserver(self, forKeyPath: "name", options: NSKeyValueObservingOptions.New, context: nil)
}
override func observeValueForKeyPath(keyPath: String?, ofObject object: AnyObject?, change: [String : AnyObject]?, context: UnsafeMutablePointer<Void>) {
if let newValue = change?[NSKeyValueChangeNewKey] {
print("Name changed: \(newValue)")
} else {
super.observeValueForKeyPath(keyPath, ofObject: object, change: change, context: context)
}
}
deinit {
self.user.removeObserver(self, forKeyPath: "name")
}
}
var user = User()
user.name = "Test"
var observer = Observer(user: user)
user.name = "Test 2"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment