Last active
March 10, 2019 20:29
-
-
Save aralshawa/e9ef34bb16c81a165677f0368e5a2173 to your computer and use it in GitHub Desktop.
A simple mechanism to check for leaky VCs.
This file contains hidden or 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
// LeakyViewControllerChecker.swift | |
// Devised by: Arek Holko | |
// Blog Post: http://holko.pl/2017/06/26/checking-uiviewcontroller-deallocation | |
extension UIViewController { | |
/// This method asserts whether a view controller gets deallocated after it disappeared due to one of these reasons: | |
/// - it was removed from its parent, or | |
/// - it (or one of its parents) was dismissed. | |
/// | |
/// **You should call this method only from UIViewController.viewDidDisappear(_:).** | |
/// - Parameter delay: Delay after which the check if a view controller got deallocated is performed | |
public func dch_checkDeallocation(afterDelay delay: TimeInterval = 2.0) { | |
#if DEBUG | |
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. a stock 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)") | |
}) | |
} | |
#endif | |
} | |
private var dch_rootParentViewController: UIViewController { | |
var root = self | |
while let parent = root.parent { | |
root = parent | |
} | |
return root | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment