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

Time:06-11

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.

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.

CodePudding user response:

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.

  • Related