Crash while creating ViewController from storyboard

I have one view in my storyboard that I am adding to the current view by doing the following:

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

storyboard

A view will appear, but everything I do after it appears will crash. What am I doing wrong?

Here is an example when it crashes:

 -(IBAction)showUsername:(id)sender{ [testLabel setText:@"username"]; } 

Everything is also connected to the storyboard, so falsely connected connections should not cause problems.

+6
source share
5 answers

You create a new view controller:

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

But you do not save it. Your view hierarchy as soon as you add it to another view.

 [self.view addSubview:mvc.view]; 

So, when the button is pressed, an IBAction message is sent to you, but your view controller has already been released. To prevent this, save the mvc variable, for example, somewhere in the property.

 @property(nonatomic, strong) MainViewController *controller; self.controller = mvc; 
+8
source

enter image description here

I can think the whole reason before you open the magazine ...

0
source

Include NSZombie in Product -> Edit Scheme, you should get a more descriptive error. Then you can add it.

0
source

Make sure your method is declared and entered correctly. Also make sure you have an IBOutlet UILabel * testLabel in your .h. The only problem I can think of is how you connected it. Failure only when a button is pressed?

0
source

This line is incorrect, so you get an error.

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

replace it with

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

In storyboards, you don’t add subview, you do one of three things that are modal, pushing it to the navigation controller stack or creating a custom one.

0
source

Source: https://habr.com/ru/post/907705/


All Articles