0

Trying to pass an array between view controllers. I am not sure why as pretty sure that the array has something in it, still when it arrives on the other side it seems to be empty. No errors... just empty.

 override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
      if segue.identifier == "segueMapSelection" {

           if let destinaton = segue.destination as? MapTableChoiceViewController {
                //destinaton.maps = sender as? [SkiMap]
                print("size of array before passing it through: ", maps.count)
                destinaton.maps = self.maps
           }
      }
     }

     @IBAction func SelectDifferentMapButton(_ sender: Any, forEvent event: UIEvent) {
          performSegue(withIdentifier: "segueMapSelection", sender: self.maps)


     }

On my receiving ViewController I have a

var maps : [ObjectTypeHere]! = []

Any idea what I am doing here? I have left the code commented of the other way I tried. When I tried that it gave an error.

Thanks for your help.

7
  • 1
    var maps : [ObjectTypeHere]! Only this in your second view controller Commented Jan 30, 2017 at 0:36
  • Ok... so I did that and it probably is showing me the problem. It now says: Fatal error: unexpectedly found nil while unwrapping an Optional value Commented Jan 30, 2017 at 0:44
  • Ok so, the arrays has the same type? Your second view controller array is ObjectTypeHere maybe you did that for the example but im asking anyway Commented Jan 30, 2017 at 0:47
  • Change this segue.destination as? MapTableChoiceViewController to this: segue.destination as! MapTableChoiceViewController i think there is the problem Commented Jan 30, 2017 at 0:48
  • 1
    Or just do: (segue.destination as! MapTableChoiceViewController).maps = self.maps only that line after checking the segue name Commented Jan 30, 2017 at 0:50

1 Answer 1

1

The issue is related to the sequence of things in view controller life cycles.

  • self.maps is collect at some point in the source VC
  • the segue begins, and reaches prepare(for segue:) occurs, which passes self.maps to the destination VC
  • only then does the destination controller (MapTableChoiceViewController) execute viewDidLoad, which (re)initializes the array

For that reason, if you declare the array as:

var maps:[ObjectTypeHere]!

You should have passed the array successfully - of course, assuming the object type between self.maps and designation.maps are the same.

For a full definition of the sequence of events, here's a detailed description.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.