Search code examples
iosswiftmemory-managementdeallocretain-cycle

Why this viewController property doesn't prevent the object from being deallocated?


Please consider the following code:

class Module {
    let viewController = ExampleViewControler()

    deinit {
        print("deinit")
    }
}

class ExampleViewControler: UIViewController {}



@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {

    var window: UIWindow?


    func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
        window = UIWindow(frame: UIScreen.main.bounds)

        let mod = Module()
        let navController = UINavigationController(rootViewController: mod.viewController)
        window?.rootViewController = navController

        window?.makeKeyAndVisible()

        return true
    }

The viewController is retained by the navController. Why is the deinit called on the Module instance? Shouldn't it be retained as well since it's property is retained?

Anyway, I would like to keep the object alive as on as it's view controller is alive. How can I achieve that?

Thank you!


Solution

  • mod variable is not retained by anyone. It's an internal variable of the function. As soon as the function exits the mod is being deallocated. No one retains it.