Objective-c – Crash when instantiating ViewController from Storyboard

iphoneobjective cstoryboard

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.

Best Answer

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;