Prepare and Perform segue throws different values

41 Views Asked by At

I want to transfer variable from first ViewController to the second one.

ViewController1:

class First_VC: UIViewController {
    
...
    @IBAction func touch(_ sender: UIButton) {
        if let indexPath = table.indexPath(for: sender.superview!.superview as! UITableViewCell) {
            let cell = table.cellForRow(at: indexPath)
            selectedName = cell?.textLabel?.text
            performSegue(withIdentifier: "segue", sender: self)
        }
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        self.searchBar.delegate = self
        self.table.dataSource =   self
    }

    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        guard segue.identifier == "segue" else { return }
        guard let vc2 = segue.destination as? Second_VC else { return }
        vc2.name = selectedName
    }
}
...

ViewController2

class Second_VC: UIViewController {
    ...

    var name: String?
    
    override func viewDidLoad() {
        super.viewDidLoad()
        print(name ?? "1")

        proName.text = name
    }
}

When i use print in the ViewController 2 i get this: (two different prints with 1sec delaying)

"1"

"Yatoro雨" -> the variable I'm looking for (works only if performSegue is added)

In my app label.text changes according to the first print that is "1" and it doesn't see the second one. How to make xCode change proName.text according to the second print?

1

There are 1 best solutions below

0
Resurrect1on- On

Some commentators below suggested to re-connect my segue through View Controller and explained why. It was the reason