gklka
gklka

Reputation: 2574

Pass variable to view controller before viewDidLoad

I perform a segue which is defined in the Storyboard to open a new view controller. I need to configure the destination view controller of the segue in a special state where some of it's buttons does not needed to be displayed.

I know that I can do this by setting a variable on this controller in my source view controller's -prepareForSegue:sender:. The problem with this is, that firstly it instantiates the controller, so it's -viewDidLoad: will run, then only after can I set anything on it.

I can't create the controller entirely from code, because it's user interface is in Storyboard. -instantiateViewControllerWithIdentifier: also calls -viewDidLoad first obviously.

I could probably use a semaphore and add the initialization code into my destination controller's -viewWillAppear, but that's ugly, it has to be some more elegant way to do this than doing a check every time the view appears. (My settings need to be done only once.)

Is there some way to pass variables into the controller before it's -viewDidLoad runs?

EDIT: It looks like this happens only if I trigger the segue from code using -performSegueWithIdentifier:.

Upvotes: 3

Views: 1770

Answers (2)

Abhinav
Abhinav

Reputation: 38162

I think there is some confusion here. -prepareForSegue:sender: gets called before -viewDidLoad gets called. Please double check your implementation.

Edit:

May be this thread will help you understand this and one of the mentioned cases fall in your case.

Upvotes: 1

Timothy Davison
Timothy Davison

Reputation: 429

On my machine and on iOS 8.0 and iOS 9.0, viewDidLoad is called after prepareForSegue. So, something like the following worked for my test case of your answer.

In your source controller:

- (void) prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
    TimViewController * controller = segue.destinationViewController;

    if( [controller isKindOfClass:[TimViewController class]] )
        controller.name = @"tim";
}

In your destination controller (TimViewController):

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do view setup here.

    NSLog( @"view did load %@", self.name );
}

Add a segue (a show segue) from your source control to the destination view controller.

Output:

2015-09-17 19:09:04.351 Test[51471:7984717] view did load tim

Upvotes: 1

Related Questions