Advertisement
Guest User

Untitled

a guest
Jan 18th, 2017
71
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.11 KB | None | 0 0
  1. class Foo: NSObject {
  2. dynamic var bar: Int = 0
  3. }
  4.  
  5. class Observer: NSObject {
  6.  
  7. private let observerKVOContext = 0
  8.  
  9. // MARK: - Objects to observe
  10.  
  11. var foo: Foo? {
  12. didSet {
  13. let observerKeyPath = #keyPath(Foo.bar)
  14. oldValue?.removeObserver(self, forKeyPath: observerKeyPath, context: &observerKVOContext)
  15. foo?.addObserver(self, forKeyPath: observerKeyPath, options: [.new, .initial, .old], context: &observerKVOContext)
  16. }
  17. }
  18.  
  19. // MARK: - Deinit
  20.  
  21. deinit {
  22. self.foo = nil
  23. }
  24.  
  25. // MARK: - KVO
  26. override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {
  27. if context == &observerKVOContext {
  28. guard let existingKeyPath = keyPath else {
  29. return
  30. }
  31. switch existingKeyPath {
  32. case #keyPath(Foo.bar):
  33. // Do KVO based update here
  34. default:
  35. return
  36. }
  37. } else {
  38. super.observeValue(forKeyPath: keyPath, of: object, change: change, context: context)
  39. }
  40. }
  41.  
  42. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement