stackich
stackich

Reputation: 5237

Unexpectedly found nil when sending data with Delegates and protocols pattern

I have 2 viewcontrollers, firstVC and secondVC.
I want to send data from the first one to update the secondVC's variable and UI.
I want to send tableView's indexPath.row with delegate when it is tapped in didSelectRowAt.
This is what I try, but when selecting a row the app crashes with error:
Unexpectedly found nil while implicitly unwrapping an Optional value
I tried to debug and saw that the delegate is nil, even if I put a method to make the delegate firstVC.
SecondVC:

func setupDelegate() {
        let FirstVC = storyboard?.instantiateViewController(identifier: "FirstVC") as! FirstVC
        FirstVC.selectionDelegate = self
    }
    
}

extension SecondVC: setSelectionDelegate {
    //this is never executed
    func didChoose(index: Int) {
        lbl.text = String(index)
    }
}

FirstVC:

protocol setSelectionDelegate {
    func didChoose(index: Int)
}

var selectionDelegate: setSelectionDelegate!

override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
     let secondVC = UIStoryboard.init(name: "Main", bundle: Bundle.main).instantiateViewController(withIdentifier: "secondVC") as? secondVC
     secondVC?.setupDelegate()
     self.selectionDelegate.didChoose(index: indexPath.row)
}

Upvotes: 1

Views: 59

Answers (1)

Dima G
Dima G

Reputation: 2025

Each time you call instantiateViewController explicitly, you get a new instance of the view controller and this is NOT the same instance that you are seeing in your device/simulator.

With storyboard segues ( embed or present modally... ) you have override prepare(...) function to get a reference to desired view controller instance.

Upvotes: 2

Related Questions