Bright Future Bright Future - 2 months ago 6
iOS Question

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
}

Answer

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