Crash when instantiating ViewController from Storyboard

房东的猫 提交于 2019-12-08 19:44:22

问题


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];

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.


回答1:


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;



回答2:


I can think all reason before you show log...




回答3:


Turn NSZombie on in the Product>>Edit Scheme you should get more descriptive Error showing then. Then you can add it.




回答4:


Make sure your method is declared and implemented correctly. Also make sure you have IBOutlet UILabel * testLabel in your .h. The only other problem I can think of other than that is how you hooked it up. Does it only crash when you press the button?




回答5:


This line is wrong this will be why you are getting the error.

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

replace it with this

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

In storyboards you are not adding a subview you are doing one of three things presenting a modal, pushing it on to the navigation controller stack or making a custom one of these.



来源:https://stackoverflow.com/questions/9150811/crash-when-instantiating-viewcontroller-from-storyboard

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!