Search code examples
iosobjective-cuiviewcontrolleruinavigationcontroller

Initialize ViewController with data and programmatically show it to screen


The storyboard of my iOS application contains a NavigationController with a root ViewController. From a secondary view controller, I would like to programmatically display the root VC with the attached NavigationController showing at the top, and at the same time instantiate the root VC with some data.

I have the following so far in the secondary view controller:

UINavigationController* nav = [[UIStoryboard storyboardWithName:@"Storyboard" bundle:nil] instantiateViewControllerWithIdentifier:@"NavController"];
UIViewController* viewController = [[UIStoryboard storyboardWithName:@"Storyboard" bundle:nil] instantiateViewControllerWithIdentifier:@"RootVC"];
viewController.data = @"My test data";

[self presentViewController:nav animated:YES completion:nil];

The root VC displays successfully with the navigation bar along the top, however when I print the following in the rootVC logic, it comes out as null:

 NSLog(@"Initialized data: %@", self.data); // null

How can I fix this? It seems that the initialized data is not coming through from the secondary controller.


Solution

  • You are creating a new instance of UIViewcontroller which has identifier "RootVC" and assigning data to it.

    Instead, you should assign the data to rootViewController of navigation controller something like this:

    self.navigationController.viewControllers.firstObject.data = @"My test data";
    

    It is a problem of different instances of same class.