Rod
Rod

Reputation: 464

Passing data to ViewController via function prepare for segue isn't working

I'm trying to pass data to a ViewController using the function:

override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
    if let vc = segue.destination as? ContactTableViewController
    {
        vc.invitationType = type
        print(vc.invitationType)
    }
}

It gets called alright, and I can print the vc.invitationType, so that variable is getting set in the new vc.

The problem is when the segue happens. In the new view controller, the line print(inv) isn't being executed, because invitationType is nil:

class ContactTableViewController: UITableViewController {

    var invitationType: InvitationType?

    override func viewDidLoad() {
        super.viewDidLoad()
        if let inv = invitationType {
            print(inv)
        }
    }
}

Can anyone explain why this is happening?

EDIT: I thought I was using the segue defined at the Storyboard, but as it turned out, I was wrongly using a function of mine that instantiates another ViewController:

    let newVC = originVC.storyboard?.instantiateViewController(withIdentifier: viewcontroller) as! VC
    let appDelegate = UIApplication.shared.delegate as! AppDelegate
    appDelegate.window?.rootViewController = newVC

So the problem was that I ended up setting the variable invitationType in one instance and segueing to a different instance of ContactTableViewController.

Upvotes: 0

Views: 453

Answers (1)

Milan Nosáľ
Milan Nosáľ

Reputation: 19737

Try this, probably the view is already loaded at that point, so viewDidLoad was called before you set the value to invitationType:

class ContactTableViewController: UITableViewController {

    var invitationType: InvitationType? {
        didSet {
            print(">>> already loaded \(invitationType)")
        }
    }

    override func viewDidLoad() {
        super.viewDidLoad()
        if let inv = invitationType {
            print(inv)
        }
    }
}

From the comments those two ContactTableViewController are not the same - you are messing up the segue somehow by instantiating another view controller that gets presented.

Upvotes: 2

Related Questions