Created
July 10, 2017 15:17
-
-
Save zvonicek/f37eb5544728b4f18d7a4e7f444cc1d9 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
extension UIViewController { | |
public func dch_checkDeallocation(afterDelay delay: TimeInterval = 2.0) { | |
let rootParentViewController = dch_rootParentViewController | |
// We don’t check `isBeingDismissed` simply on this view controller because it’s common | |
// to wrap a view controller in another view controller (e.g. in UINavigationController) | |
// and present the wrapping view controller instead. | |
if isMovingFromParentViewController || rootParentViewController.isBeingDismissed { | |
let type = type(of: self) | |
let disappearanceSource: String = isMovingFromParentViewController ? "removed from its parent" : "dismissed" | |
DispatchQueue.main.asyncAfter(deadline: .now() + delay, execute: { [weak self] in | |
assert(self == nil, "\(type) not deallocated after being \(disappearanceSource)") | |
}) | |
} | |
} | |
private var dch_rootParentViewController: UIViewController { | |
var root = self | |
while let parent = root.parent { | |
root = parent | |
} | |
return root | |
} | |
} | |
private let swizzling: (UIViewController.Type) -> () = { viewController in | |
let originalSelector = #selector(viewController.viewDidDisappear(_:)) | |
let swizzledSelector = #selector(viewController.proj_viewDidDisappear(animated:)) | |
let originalMethod = class_getInstanceMethod(viewController, originalSelector) | |
let swizzledMethod = class_getInstanceMethod(viewController, swizzledSelector) | |
method_exchangeImplementations(originalMethod, swizzledMethod) | |
} | |
extension UIViewController { | |
open override class func initialize() { | |
// make sure this isn't a subclass | |
guard self === UIViewController.self else { return } | |
swizzling(self) | |
} | |
// MARK: - Method Swizzling | |
func proj_viewDidDisappear(animated: Bool) { | |
self.proj_viewDidDisappear(animated: animated) | |
dch_checkDeallocation() | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment