Bright
Bright

Reputation: 5751

Can't change an instance of view controller's property

I have this button in my first view controller, when you press it, it triggers 2 action:

  • a function iterateItems
  • a segue which animates to ResultViewController

I need to set dataSource of ResultViewController to bestComposition in order to complete its view, and the value of this property can only be obtained after iterateItems is finished, I put this code in iterateItems:

print(bestComposition.count)
let resultVC = ResultViewController()
resultVC.dataSource = bestComposition

However, in the viewDidAppear method of ResultViewController, value of dataSource is not changed, here's the ResultViewController:

var dataSource = [WeaponItems]()
override func viewDidAppear(_ animated: Bool) {
    print(dataSource.count)
    ...
}

The value of dataSource is 3 in ViewController, but is always 0 in ResultViewController, why doesn't it change?

Edit (Code for prepare for segue):

override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
    let secondVC = segue.destination as! ResultViewController
    secondVC.transitioningDelegate = self
    secondVC.modalPresentationStyle = .custom
}

Upvotes: 0

Views: 36

Answers (2)

Bista
Bista

Reputation: 7903

Try this:

override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
    let secondVC = segue.destination as! ResultViewController
    secondVC.transitioningDelegate = self
    secondVC.modalPresentationStyle = .custom
    secondVC.dataSource = bestComposition
}

Upvotes: 0

pbasdf
pbasdf

Reputation: 21536

resultVC is AN instance of ResultViewController, newly created by this line:

let resultVC = ResultViewController()

It's not THE instance that is created automatically as part of the segue. resultVC is never displayed, so it's viewDidAppear never runs, and so the print statement is never executed. Meanwhile, the instance created by the segue is presented, so it's viewDidAppear does run - but the value for its dataSource is unchanged. Try:

let resultVC = segue.destinationViewController as! ResultViewController

Upvotes: 1

Related Questions