为什么这个 viewController 属性 不能阻止对象被释放?
Why this viewController property doesn't prevent the object from being deallocated?
请考虑以下代码:
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
}
viewController 由 navController 保留。为什么在 Module 实例上调用 deinit?既然保留了属性,难道不应该也保留吗?
无论如何,我想让对象保持活动状态,因为它的视图控制器处于活动状态。我怎样才能做到这一点?
谢谢!
mod
变量没有被任何人保留。它是函数的内部变量。一旦函数退出,mod
就会被释放。没有人保留它。
请考虑以下代码:
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
}
viewController 由 navController 保留。为什么在 Module 实例上调用 deinit?既然保留了属性,难道不应该也保留吗?
无论如何,我想让对象保持活动状态,因为它的视图控制器处于活动状态。我怎样才能做到这一点?
谢谢!
mod
变量没有被任何人保留。它是函数的内部变量。一旦函数退出,mod
就会被释放。没有人保留它。