ViewController被取消分配,导致崩溃

the*_*tic 4 iphone objective-c storyboard uiviewcontroller automatic-ref-counting

我在我的故事板中有一个视图,我分配了一个名为"MainView"的标识符.但是,如果我将其视图添加到子视图,则后面的所有内容都会导致崩溃(例如,按下按钮)

MainViewController *mvc = [self.storyboard instantiateViewControllerWithIdentifier:@"MainView"];
             [self.view addSubview:mvc.view];
Run Code Online (Sandbox Code Playgroud)

这是按钮触发的动作:(MainViewController.h)

-(IBAction)showUsername:(id)sender{

    [testLabel setText:@"username"];

}
Run Code Online (Sandbox Code Playgroud)

和崩溃日志:

-[MainViewController performSelector:withObject:withObject:]: message sent to deallocated instance 0x44e0810
Run Code Online (Sandbox Code Playgroud)

我用ARC.

Sim*_*ain 6

处理此问题的最佳方法是使用财产.这是如何做:

在你的.h文件中:

#import "MainViewController.h"

@interface MyClass : UIViewController

@property (strong, nonatomic) MainViewController *mvc;

@end
Run Code Online (Sandbox Code Playgroud)

在.m文件中:

#import "MyClass.h"

@implementation MyClass

@synthesize mvc;

// Your code here
- (void)yourMethodHere {
    self.mvc = [self.storyboard instantiateViewControllerWithIdentifier:@"MainView"];
    [self.view addSubview:mvc.view];
}
Run Code Online (Sandbox Code Playgroud)