Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Crash when trying to update the UI on a previous view controller

Alright I have view controller A that presents view controller B like so…

@IBAction func presentView(_ sender: Any) {
    let storyBoard : UIStoryboard = UIStoryboard(name: "main", bundle:nil)
    let vc = storyBoard.instantiateViewController(withIdentifier: "Popout") as! PopoutWindow
    vc.modalTransitionStyle = .coverVertical
    vc.modalPresentationStyle = .overFullScreen
    self.present(vc, animated:true, completion:nil)
}

When I’m done with view controller B, I dismiss it like so…

let vc = WellnessPlanEnrollmentController()
self.dismiss(animated: true, completion: {
vc.refreshView()
})

And then the function I’m calling is attempting to update my UI with the new data from view controller B. However, when I reload the first view, I get a weird crash saying that my label I’m trying to update is nil.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

func refreshView() {
    DispatchQueue.main.async {
        self._petNameLabel.text = self.object.name
        // crashes here because my label is nil???????
    }
}

Error: FirstViewController.swift:128: Fatal error: Unexpectedly found nil while implicitly unwrapping an Optional value

I feel like it’s because the view is not in focus when I’m calling the function but I’m not sure.

>Solution :

This is failing because you create a new instance of WellnessPlanEnrollmentController. This instance is not connected to any Storyboard or View so all of its outlets are nil.

Possible solution:

Create a delegate in your controller B and assign it before presenting and call it after dismiss.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading