1
votes

I am have a ContainerVC which holds a variable controllerToLoad. By Default it is "MainVC" however when clicking on a menu item, I wish to present the ContainerVCbut instead of loading MainVC, I wish to load SecondVC. I load the MainVC in the ViewDidLoad method of my ContainerVC by doing the following:

if let controller = self.storyboard?.instantiateViewControllerWithIdentifier(controllerToLoad) {
    self.mainViewController = controller
}

I thought the best way to do this is by segue, so I call the following lines of code:

self.performSegueWithIdentifier("MenuSegue", sender: self)

Then in my prepareForSegue I do the following:

if (segue.identifier == "MenuSegue"){
   let secondViewController = segue.destinationViewController as! ContainerViewController
   secondViewController.controllerToLoad = "SecondVC"
}

For some reason, when calling performSegueWithIdentifier it automatically loads the ContainerVC and starts to sets self.mainViewController to "MainVC" instead of waiting for prepareForSegue to run. I don't know why its not waiting for prepareForSegue to finish.

I tested this by adding bunch of print statements. right before self.performSegueWithIdentifier and before secondViewController.controllerToLoad = "SecondVC" and in ViewDidLoad of my ContainerVC. After adding the print statements I realized that in fact as soon as performSegueWithIdentifier is called, right after it calls ViewDidLoad of ContainerVC then performs

let secondViewController = segue.destinationViewController as! ContainerViewController secondViewController.controllerToLoad = "SecondVC"

2

2 Answers

1
votes

This is the correct and to be expected behaviour. In prepareForSegue you can access the destinationViewController and its properties, including UIView elements, so logically the view must have already been loaded. Hence, viewDidLoad will have been called.

You could use another method, such as viewWillAppear, which executes after prepareForSegue but it seems that a different approach would be better. Perhaps a method on your container view controller that told it to load and present a new VC.

0
votes

I think, you don't need to do both these things. You instantiate mainController, but when you perfromSegue MainSegue there is second instance of mainController created and you have wrong view life cycle events method calls sequence. you either must push mainController by pushViewController:animated or don't create it at all.