ViewController 被释放,导致崩溃

发布于 2025-01-03 06:02:01 字数 600 浏览 2 评论 0原文

我的故事板中有一个视图,我为其分配了一个名为“MainView”的标识符。但是,如果我将其视图添加到子视图中,则接下来的所有内容都会产生崩溃(例如按下按钮)

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

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

-(IBAction)showUsername:(id)sender{

    [testLabel setText:@"username"];

}

和崩溃日志:

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

我使用ARC。

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

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

-(IBAction)showUsername:(id)sender{

    [testLabel setText:@"username"];

}

and the crash log :

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

I use ARC.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

绝不放开 2025-01-10 06:02:01

处理这个问题的最佳方法是使用属性。操作方法如下:

在 .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];
}

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

In your .h file:

#import "MainViewController.h"

@interface MyClass : UIViewController

@property (strong, nonatomic) MainViewController *mvc;

@end

In your .m file:

#import "MyClass.h"

@implementation MyClass

@synthesize mvc;

// Your code here
- (void)yourMethodHere {
    self.mvc = [self.storyboard instantiateViewControllerWithIdentifier:@"MainView"];
    [self.view addSubview:mvc.view];
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文