Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- class Foo: NSObject {
- dynamic var bar: Int = 0
- }
- class Observer: NSObject {
- private let observerKVOContext = 0
- // MARK: - Objects to observe
- var foo: Foo? {
- didSet {
- let observerKeyPath = #keyPath(Foo.bar)
- oldValue?.removeObserver(self, forKeyPath: observerKeyPath, context: &observerKVOContext)
- foo?.addObserver(self, forKeyPath: observerKeyPath, options: [.new, .initial, .old], context: &observerKVOContext)
- }
- }
- // MARK: - Deinit
- deinit {
- self.foo = nil
- }
- // MARK: - KVO
- override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {
- if context == &observerKVOContext {
- guard let existingKeyPath = keyPath else {
- return
- }
- switch existingKeyPath {
- case #keyPath(Foo.bar):
- // Do KVO based update here
- default:
- return
- }
- } else {
- super.observeValue(forKeyPath: keyPath, of: object, change: change, context: context)
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement