ViewController被释放,导致崩溃 [英] ViewController gets deallocated which leads to crash

查看:76
本文介绍了ViewController被释放,导致崩溃的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的情节提要中有一个视图,该视图分配了一个名为"MainView"的标识符.但是,如果我将其视图添加到子视图中,则随后的所有操作都会导致崩溃(例如,按下按钮)

I have a view in my storyboard which I assigned an identifier called "MainView". However if I add its view to the subview, everything that follows produces a crash (e.g. pressing a button)

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

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

This is the action triggered by the button : (MainViewController.h)

-(IBAction)showUsername:(id)sender{

    [testLabel setText:@"username"];

}

和崩溃日志:

-[MainViewController performSelector:withObject:withObject:]: message sent to deallocated instance 0x44e0810

我使用ARC.

推荐答案

处理此问题的最佳方法是使用属性.方法如下:

Best way to deal with this is using a property. Here's how:

在您的.h文件中:

#import "MainViewController.h"

@interface MyClass : UIViewController

@property (strong, nonatomic) MainViewController *mvc;

@end

在您的.m文件中:

#import "MyClass.h"

@implementation MyClass

@synthesize mvc;

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

这篇关于ViewController被释放,导致崩溃的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆