从Storyboard实例化ViewController时崩溃 [英] 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];
该视图出现了,但是出现后我所做的一切都会导致崩溃.我在做什么错了?
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.
推荐答案
您实例化一个新的视图控制器:
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];
因此,当单击按钮时,一条消息会发送给您 IBAction
,但是您的视图控制器已被释放.为了防止这种情况发生,请保留您的 mvc
变量,例如在属性中的某个位置.
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;
这篇关于从Storyboard实例化ViewController时崩溃的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!