Created
March 16, 2025 07:10
-
-
Save lanserxt/2f7ea59a486c0ebe13eac0c690cf1264 to your computer and use it in GitHub Desktop.
UIKit deinit isolation implementation
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
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