【问题标题】:Why is this object being prematurely deallocated under ARC?为什么这个对象在 ARC 下被过早地释放?
【发布时间】:2012-03-18 06:34:33
【问题描述】:

我在为 UIButton 设置目标时遇到问题:

//  TestViewController.m
@implementation TestViewController

@synthesize scrollContentView

- (void)viewDidLoad
{
    [super viewDidLoad];
 SecondViewController *secondViewController = [self.storyboard instantiateViewControllerWithIdentifier:@"SecondViewController"];

[self.scrollContentView addSubview:secondViewController.view];
}

@end

// SecondViewController.m
- (void)viewDidLoad
{
    [super viewDidLoad];
    UIButton *button1 = [UIButton buttonWithType:UIButtonTypeRoundedRect];
    [button1 addTarget:self action:@selector(button1Click:) forControlEvents:UIControlEventTouchUpInside];
    button1.frame = CGRectMake(20, 45, 280, 40);
    [self.view addSubview:button1];
}

- (IBAction)button1Click:(id)sender
{
    NSLog(@"test");
}

问题是当我单击按钮时,我收到以下错误消息:

[SecondViewController performSelector:withObject:withObject:]: 消息 发送到释放的实例 0x685c050

(lldb)

我假设问题是我只是将一个视图传递给 UIScrollView 并且我无法访问控制器。

知道如何解决这个问题吗?

【问题讨论】:

    标签: ios uiscrollview uibutton automatic-ref-counting


    【解决方案1】:

    消息“message sent to deallocated instance”表示您的secondViewController 变量在viewDidLoad 末尾超出范围时未保留 但是它的视图,其中包含它的按钮,是。指向一个带有指向死对象的指针的活对象。因此你的崩溃。

    由于您使用的是 ARC,因此最快(可能是 hackie)的方法是在 TestViewController 的 ivar 中创建 SecondViewController

    @implementation TestViewController{
        SecondViewController *secondViewController; // with ARC ivars are strong by default
    }
    

    然后将viewDidLoad中的行改为:

    secondViewController = [self.storyboard instantiateViewControllerWithIdentifier:@"SecondViewController"];
    

    但我相信正确的方法(当然我不知道你的应用程序的细节)可能是使用:

    - (void)addChildViewController:(UIViewController *)childController __OSX_AVAILABLE_STARTING(__MAC_NA,__IPHONE_5_0);
    

    如果这是 iPhone/iPod touch 应用程序,请注意; Apple 曾表示,对于这些设备,比例通常应该是一个视图控制器对一个屏幕内容。再说一次,我不知道你的应用的细节,只是想提一下。

    【讨论】:

    • 感谢 NJones。第一个解决方案没有奏效,但第二个解决了。
    猜你喜欢
    • 2012-01-30
    • 1970-01-01
    • 2010-12-18
    • 2012-03-12
    • 1970-01-01
    • 1970-01-01
    • 2015-08-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多