【问题标题】:ViewController gets deallocated which leads to crashViewController 被释放导致崩溃
【发布时间】:2012-02-27 10:28:31
【问题描述】:

我的故事板中有一个视图,我为它分配了一个名为“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。

【问题讨论】:

  • instantiateViewControllerWithIentifier:创建一个自动释放的对象。你必须在这里-retain它,并在不再需要它时释放它。
  • 我用的是ARC,所以不支持调用retain ...

标签: iphone objective-c uiviewcontroller storyboard automatic-ref-counting


【解决方案1】:

解决此问题的最佳方法是使用属性。方法如下:

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

【讨论】:

  • 我考虑过这样做,但我使用 ARC,所以我不能真正对任何对象调用 retain。
  • 暂别我所说的...使用属性将避免您遇到的问题。
  • 虽然这样可以避免问题,但是谁能解释一下为什么会这样?
猜你喜欢
  • 2011-08-07
  • 1970-01-01
  • 1970-01-01
  • 2011-07-02
  • 1970-01-01
  • 2022-01-05
  • 1970-01-01
  • 1970-01-01
  • 2011-12-31
相关资源
最近更新 更多