Tommy K Tommy K - 3 months ago 20x
iOS Question

Passing an object through a root view controller

I have a programmatically created

which I want to trigger a modal segue to a Navigation Controller. The Nav Controller is the "root view controller" to my Edit View Controller Scene.

Here is an example of what I'm talking about, except here the button is created in the storyboard and thus you can control-drag the segue from the button in the storyboard. This is the structure I'm talking about

HomeVC --(modal)--> Navigation Controller --(root view)--> EditVC

I can't insert a
in my storyboard, so I have to create one programmatically and made the segue to the Navigation Controller following this answer.

My purpose here is to present a modal screen to edit an object, so I need to pass that object from my HomeVC into my EditVC thru the Navigation Controller. The example in the first link was to create an object, so nothing needed to get passed.

Here's where I am now. My HomeVC (simplifying names so its easier to understand) has a navbar with a programmatically created
whose selector calls a function:

func editButtonPressed() {
// doesn't call prepareForSegue unless I prepend super.
super.performSegueWithIdentifier("ShowEdit", sender: self)

My trouble lies inside my prepareForSegue function:

override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
print("this one prints")
if segue.identifier == "ShowEdit" {
print("this one prints")
// prints out the UINavigationController, not the EditVC
print("segue: \(segue.destinationViewController)")
if let editViewController = segue.destinationViewController as? EditViewController {
editViewController.selectedObject = selectedObject
} else {
print("this one prints")

So if you can see what I'm getting at, I want to pass the object from HomeVC to EditVC, but my segue is currently going to the Navigation root view controller. How can I pass it through the navigation controller to the EditVC?

I thought about creating a controller for the Nav Controller, so it would be
myNavVC.selectedObject == selectedObject
, and then in myNavVC's prepareForSegue pass it on with
EditVC.selectedObject == selectedObject
, but what would I use for the identifier since its a root view?


Demo it in Objective-C:

UINavigationController *navigationController = (UINavigationController*)segue.destinationViewController;

EditViewController *editViewController = (EditViewController *)[[navigationController viewControllers] firstObject];

editViewController.selectedObject = selectedObject;

Demo in Swift:

var navigationController: UINavigationController = (segue.destinationViewController as! UINavigationController)
var editViewController: EditViewController = (navigationController.viewControllers.first! as! EditViewController)
editViewController.selectedObject = selectedObject