Last active
December 19, 2018 09:35
-
-
Save danurna/3b0c2ac973d07877a882644beec7e250 to your computer and use it in GitHub Desktop.
AttachingObserver (Weak KVO)
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
// Based on https://gist.github.com/joerick/a0b87607e69071fa6a3c | |
class AttachingObserver: NSObject { | |
typealias ChangeHandler = (NSObject, [NSKeyValueChangeKey: Any]?) -> Void | |
weak var observedObject: NSObject? | |
let keyPath: String | |
let changeHandler: ChangeHandler | |
init(observe object: NSObject, keyPath: String, changeHandler: @escaping ChangeHandler) { | |
self.observedObject = object | |
self.keyPath = keyPath | |
self.changeHandler = changeHandler | |
super.init() | |
object.addObserver(self, forKeyPath: keyPath, options: [.initial, .new], context: nil) | |
objc_setAssociatedObject(object, "observer", self, objc_AssociationPolicy.OBJC_ASSOCIATION_RETAIN_NONATOMIC) | |
} | |
deinit { | |
observedObject?.removeObserver(self, forKeyPath: keyPath) | |
} | |
override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey: Any]?, context: UnsafeMutableRawPointer?) { | |
if keyPath == self.keyPath { | |
changeHandler(object as! NSObject, change) | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment