Removing a view controller from memory when instan

2019-04-05 18:52发布

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.

I have tried doing

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.

1条回答
姐就是有狂的资本
2楼-- · 2019-04-05 19:18

You need only to use:

EDIT Swift 4.2

self.dismiss(animated:true, completion: nil)

The rest of work is doing by ARC

To help you during your debug you can add also this code:

 if let app = UIApplication.shared.delegate as? AppDelegate, let window = app.window {
        if let viewControllers = window.rootViewController?.children {
            for viewController in viewControllers {
                print(viewController.debugDescription)
            }
        }
    }
查看更多
登录 后发表回答