简体   繁体   中英

Is a ViewController unloaded from memory after being dismissed?

I noticed that the state of variables doesn't preserve among different presentations of a View Controller.

    var starrySky = StarrySky() // this has a state property which is false initially
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        if starrySky.state == false { starrySky.createSky(for: self.view) }
        if starrySky.state != false { starrySky.resumeSkyAnimations()} // this never runs

    }
    override func viewWillDisappear(_ animated: Bool) {
        super.viewWillDisappear(animated)
        starrySky.state = true // here im changing the state
        starrySky.removeSkyAnimations()
    }

So whenever I dismiss this ViewController and present it again my starrySky.state is always false. I have the same code in the same methods in my rootViewController and whenever I change views the state preserves.

  • So does this mean that any VC's presented modally are dismissed from memory after you call dismiss(animated:,completion:) ?

So does this mean that any VC's presented modally are dismissed from memory after you call dismiss

Normally, yes. View controllers form a hierarchy or chain of parent/presenter and child/presented. The former owns and retains the latter, and releases it when the latter is removed. The root controller is never removed unless you deliberately replace it.

Because when you present the view again the variable starrySky is initialized again with false you can save the state using userDefaults in viewWillDisappear and read it in viewWillAppear

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM