0

我有一个视图控制器,它的打开UIViewController方式UIViewPicker如下:

-(void)operationClicked:(id)sender {
    ChoseOperationViewController *picker = [[ChoseOperationViewController alloc] initWithNibName:@"ChoseOperationViewController" bundle:[NSBundle mainBundle]];
    [self.view addSubview:picker.view];
    [picker animateSlideOut];
}

ChoseOperationViewController 是自定义的 UiViewController 类,其 nib 持有UiViewPickerUINavigationBar

我已将“Anuluj”(取消)按钮连接到操作,如下图所示: 在此处输入图像描述

当我点击按钮时,我得到了-[ChoseOperationViewController performSelector:withObject:withObject:]: message sent to deallocated instance 0x7569fd0并且 cancelClicked 方法没有被调用。这是为什么?

4

1 回答 1

0

问题:

-(void)operationClicked:(id)sender {
    ChoseOperationViewController *picker = [[ChoseOperationViewController alloc] initWithNibName:@"ChoseOperationViewController" bundle:[NSBundle mainBundle]];
    [self.view addSubview:picker.view];
    [picker animateSlideOut];
}

这将创建一个实例ChoseOperationViewController并将其视图作为子视图添加到self.view. 但是当方法-(void)operationClicked:(id)sender返回时,您对刚刚创建的实例没有强引用 - 因此 ARC 将释放它。

当用户触摸取消按钮时,它会尝试将消息发送到被释放的实例并且应用程序崩溃。

解决方案:

将实例变量添加到您的UIViewController

@implementation MyViewController {
    ChoseOperationViewController *picker;
}

并将您的代码更改operationClicked为:

-(void)operationClicked:(id)sender {
    if(!picker) {
         picker = [[ChoseOperationViewController alloc] initWithNibName:@"ChoseOperationViewController" bundle:[NSBundle mainBundle]];
         [self.view addSubview:picker.view];
    }
    [picker animateSlideOut];
}

这将防止ChoseOperationViewController实例被释放

于 2013-03-13T15:37:51.767 回答