Skip to content

Instantly share code, notes, and snippets.

@dimohamdy
Last active January 2, 2019 15:44
Show Gist options
  • Save dimohamdy/ffd0ee9396a753699ff5a019d688d241 to your computer and use it in GitHub Desktop.
Save dimohamdy/ffd0ee9396a753699ff5a019d688d241 to your computer and use it in GitHub Desktop.
Check Retain Cycle in ViewController
//I get this code from Arek Holko artival https://holko.pl/2017/06/26/checking-uiviewcontroller-deallocation/
import UIKit
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 typeValue = 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, "\(typeValue) not deallocated after being \(disappearanceSource)")
})
}
}
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