为什么这个viewController属性不会阻止对象被释放?

时间:2017-03-13 08:12:55

标签: ios swift memory-management dealloc retain-cycle

请考虑以下代码:

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
    }

navController保留viewController。为什么在模块实例上调用deinit?它不应该被保留,因为它的财产被保留了吗?

无论如何,我想让对象保持活着,因为它的视图控制器还活着。我怎样才能做到这一点?

谢谢!

1 个答案:

答案 0 :(得分:2)

任何人都不会保留

mod变量。它是函数的内部变量。函数退出后,mod将被解除分配。没有人保留它。