Created
January 16, 2019 08:13
-
-
Save ha1f/f519a4d4cbb77f5ff3cdfebaf1f1959b to your computer and use it in GitHub Desktop.
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
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