Skip to content

Instantly share code, notes, and snippets.

@ha1f
Created January 16, 2019 08:13
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ha1f/f519a4d4cbb77f5ff3cdfebaf1f1959b to your computer and use it in GitHub Desktop.
Save ha1f/f519a4d4cbb77f5ff3cdfebaf1f1959b to your computer and use it in GitHub Desktop.
final class DeallocNotifier {
private var _observers: [() -> Void] = []
func observe(_ observer: @escaping () -> Void) {
_observers.append(observer)
}
deinit {
_observers.forEach { observer in
observer()
}
}
}
private var deallocNotifierContext: UInt8 = 0
extension NSObject {
var deallocNotifier: DeallocNotifier {
/// This is a technique to use getter as if this object has additional property
if let notifier = objc_getAssociatedObject(self, &deallocNotifierContext) as? DeallocNotifier {
return notifier
}
let notifier = DeallocNotifier()
objc_setAssociatedObject(self, &deallocNotifierContext, notifier, .OBJC_ASSOCIATION_RETAIN_NONATOMIC)
return notifier
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment