Guest User

Untitled

a guest
Jan 16th, 2019
101
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.77 KB | None | 0 0
  1. final class DeallocNotifier {
  2. private var _observers: [() -> Void] = []
  3.  
  4. func observe(_ observer: @escaping () -> Void) {
  5. _observers.append(observer)
  6. }
  7.  
  8. deinit {
  9. _observers.forEach { observer in
  10. observer()
  11. }
  12. }
  13. }
  14.  
  15. private var deallocNotifierContext: UInt8 = 0
  16.  
  17. extension NSObject {
  18. var deallocNotifier: DeallocNotifier {
  19. /// This is a technique to use getter as if this object has additional property
  20. if let notifier = objc_getAssociatedObject(self, &deallocNotifierContext) as? DeallocNotifier {
  21. return notifier
  22. }
  23. let notifier = DeallocNotifier()
  24. objc_setAssociatedObject(self, &deallocNotifierContext, notifier, .OBJC_ASSOCIATION_RETAIN_NONATOMIC)
  25. return notifier
  26. }
  27. }
Add Comment
Please, Sign In to add comment