Created
August 6, 2015 18:13
-
-
Save Ben-G/31359abe4797a7182d96 to your computer and use it in GitHub Desktop.
Simple KVO example in Swift based on: http://stackoverflow.com/questions/24092285/is-key-value-observation-kvo-available-in-swift
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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