Search code examples
iosstoryboardsegueviewcontrollerviewdidload

ViewController from StoryBoard make ViewDidLoad called twice


I would like to make (from my StoryBoard) a ViewController that I will be able to push from anywhere by code (this ViewController will be used a lot of time, so I don't wan't to add tons of segues in the StoryBoard...).

I also have to pass some variables from the current ViewController to the pushed one. To do it I'm using this code :

NBItemDetailsViewController *vc = [self.storyboard instantiateViewControllerWithIdentifier:@"ItemDetailsViewController"];
vc.item = self.selectedItem;
[self.navigationController pushViewController:vc animated:YES];

It nearly works, but in the pushed ViewController, the viewDidLoad method is called twice. The first time, I can get the item, but the second, it is null. Of course it seems like the displayed ViewController is the one of the second call, and I can't get my item.

Any idea ? Is there a better option, using segues in the StoryBoard (I can't believe there is no way to reuse a ViewController in the StoryBoard...) ?

PS : I already tried to use viewDidAppear.


Solution

  • You might create a subclass of UIViewController (MyRegularViewController) and assign a .xib by (MyRegularViewController.xib)

    File > New > File > User Interface > Empty

    and drag a UIViewController to your emtpy xib file. Associate your MyRegularViewController with that xib, then customize it.

    Now you can use it anywhere you want simply like this;

    MyRegularViewController *regular = [[MyRegularViewController alloc] initWithNibName:@"MyRegularViewController" bundle:nil];
    self.navigationController pushViewController:regular animated:YES];
    

    You are not obligated to use storyboard in all cases, in fact using your storyboard for something like this situation will mess your storyboard. Simply use a xib and a custom class for this.