Skip to content

Instantly share code, notes, and snippets.

@lanserxt
Created March 16, 2025 07:10
Show Gist options
  • Save lanserxt/2f7ea59a486c0ebe13eac0c690cf1264 to your computer and use it in GitHub Desktop.
Save lanserxt/2f7ea59a486c0ebe13eac0c690cf1264 to your computer and use it in GitHub Desktop.
UIKit deinit isolation implementation
import UIKit
class ParentViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
let childVC = ChildViewController()
displayContentController(content: childVC)
}
func displayContentController(content: UIViewController) {
addChild(content)
self.view.addSubview(content.view)
content.didMove(toParent: self)
}
deinit {
// ❌ This will cause an error in Swift 6 strict concurrency mode
children.forEach { child in
child.willMove(toParent: nil)
child.view.removeFromSuperview()
child.removeFromParent()
}
}
}
class FixedParentViewController: UIViewController {
private weak var childVC: ChildViewController?
override func viewDidLoad() {
super.viewDidLoad()
let childVC = ChildViewController()
displayContentController(content: childVC)
self.childVC = childVC
}
func displayContentController(content: UIViewController) {
addChild(content)
self.view.addSubview(content.view)
content.didMove(toParent: self)
}
deinit {
//MainActor isolation and no strong self capture
Task { @MainActor [childVC] in
childVC?.willMove(toParent: nil)
childVC?.view.removeFromSuperview()
childVC?.removeFromParent()
}
}
}
class ChildViewController: UIViewController {}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment