Created
August 2, 2017 10:42
-
-
Save mspvirajpatel/81d6ab58d43d1a074e13a80c5d14dbe0 to your computer and use it in GitHub Desktop.
KVO Demo
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 | |
typealias KVOContext = UInt8 | |
var MyObservationContext = KVOContext() | |
class Observer: NSObject { | |
func startObservingPerson(person: Person) { | |
let options = NSKeyValueObservingOptions([.New, .Old]) | |
person.addObserver(self, forKeyPath: "firstName", options: options, context: &MyObservationContext) | |
person.addObserver(self, forKeyPath: "lastName", options: options, context: &MyObservationContext) | |
} | |
func stopObservingPerson(person: Person) { | |
person.removeObserver(self, forKeyPath: "firstName", context: &MyObservationContext) | |
person.removeObserver(self, forKeyPath: "lastName", context: &MyObservationContext) | |
} | |
override func observeValueForKeyPath(keyPath: String?, ofObject object: AnyObject?, change: [NSObject : AnyObject]?, context: UnsafeMutablePointer<Void>) { | |
guard keyPath != nil else { | |
super.observeValueForKeyPath(keyPath, ofObject: object, change: change, context: context) | |
return | |
} | |
switch (keyPath!, context) { | |
case("firstName", &MyObservationContext): | |
print("First name changed: \(change)") | |
case("lastName", &MyObservationContext): | |
print("Last name changed: \(change)") | |
case(_, &MyObservationContext): | |
assert(false, "unknown key path") | |
default: | |
super.observeValueForKeyPath(keyPath, ofObject: object, change: change, context: context) | |
} | |
} | |
} | |
class Person: NSObject { | |
dynamic var firstName: String? | |
dynamic var lastName: String? | |
} | |
let person = Person() | |
let observer = Observer() | |
observer.startObservingPerson(person) | |
person.firstName = "Jim" | |
person.lastName = "Correia" | |
observer.stopObservingPerson(person) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment