在实例化新视图控制器时从内存中删除视图控制器 [英] Removing a view controller from memory when instantiating a new view controller
问题描述
在我的应用程序中,我实例化新的视图控制器而不是使用segues,因为它在动画中看起来更好,因此我的视图在后台继续运行。这会导致大量内存泄漏。
In my app, I am instantiating new view controllers instead of using segues because it looks better in animations as a result, my views keep running in the background. This causes large memory leaks.
我回到主屏幕的代码是:
My code to go back to the main screen is:
let mainStoryboard = UIStoryboard(name: "Main", bundle: NSBundle.mainBundle())
let vc : UIViewController = mainStoryboard.instantiateViewControllerWithIdentifier("MainScreen") as UIViewController
self.presentViewController(vc, animated: false, completion: nil)
此视图控制器在后台仍处于活动状态因此不应再次实例化。我该怎么做。
This view controller is still active in the background and therefore shouldn't be instantiated again. How do I do this.
当我使用上面的代码关闭我的视图控制器时,它也不会卸载它,它会一直在后台运行。如何在屏幕消失后立即卸载。
When I close my view controller using the above code, it also does not unload it, it keeps running in the background. How do I make it unload as soon as the screen disappears.
我试过了
override func viewDidDisappear(animated: Bool) {
super.viewDidDisappear(animated)
view.removeFromSuperview()
view = nil
}
但是这不能正常工作。以这种方式退出视图控制器时,如何从内存中正确销毁视图控制器。
However this does not work properly. How do I properly destroy a view controller from memory when exiting a view controller in this manner.
推荐答案
您只需要使用:
self.dismissViewControllerAnimated(true, completion: {})
其余工作是通过 ARC
为了在调试过程中为您提供帮助,您还可以添加以下代码:
To help you during your debug you can add also this code:
if let app = UIApplication.sharedApplication().delegate as? AppDelegate, let window = app.window {
if let viewControllers = window.rootViewController?.childViewControllers {
for viewController in viewController
print(viewController.debugDescription)
}
}
}
这篇关于在实例化新视图控制器时从内存中删除视图控制器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!