Search code examples
iosuiviewcontrolleruinavigationcontrollerstoryboardpushviewcontroller

iOS pass data when using storyboard to push the view controller


I am starting to use storyboard more often but I have run into a problem. Usually when you push a view controller using a UINavigationController you do it in the following way and you are able to pass data along with it:

UIViewController *vc = [[UIViewController alloc] init];
vc.link = [self link];
vc.name = [self name];

UINavigationController *nav = [[UINavigationController alloc] initWithRootViewController:vc]
[nav presentViewController:vc completion:nil animated:YES];

(I did the above code for memory so it may not be 100% correct).

Now that I am using storyboard, I am not instantiating the view controllers myself so how do I pass data with it? Thanks!


Solution

  • Use the prepareForSegue:sender: method.

    For example:

    - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
    {
        if ([segue.identifier isEqualToString:@"SegueID"])
        {
            UIViewController * vc = segue.destinationViewController;
            vc.link = [self link];
            vc.name = [self name];
        }
    }
    

    Or, if your destination view controller is a UINavigationController, use this:

    UINavigationController * navigationController = segue.destinationViewController;
    UIViewController * vc = [navigationController.viewControllers objectAtIndex:0];