Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Crash when instantiating ViewController from Storyboard

I have got a single view in my storyboard, which I add to my current view by doing the following :

MainViewController *mvc = [self.storyboard instantiateViewControllerWithIdentifier:@"MainController"];
             [self.view addSubview:mvc.view];

storyboard

The view appears, but everything I do after it appears, leads to a crash. What am I doing wrong ?

Here is an example when it crashes:

-(IBAction)showUsername:(id)sender{

    [testLabel setText:@"username"];

}

Everything is hooked up in storyboard as well, so falsely linked connections should not cause the problem.

like image 661
the_critic Avatar asked Feb 05 '12 16:02

the_critic


1 Answers

You instantiate a new view controller:

MainViewController *mvc = [self.storyboard instantiateViewControllerWithIdentifier:@"MainController"];

But you do not retain it. Your view hierarchy is, as soon you added it to another view.

[self.view addSubview:mvc.view];

So when a button is clicked, a message is sent to you IBAction, but your view controller has been released already. To prevent this from happening, retain your mvc variable, for example somewhere in a property.

@property(nonatomic, strong) MainViewController *controller;

self.controller = mvc;
like image 58
Joris Kluivers Avatar answered Sep 22 '22 13:09

Joris Kluivers