单击导航项上的BAD_ACCESS

时间:2013-03-13 15:07:54

标签: ios uinavigationbar

我有一个视图控制器,可以UIViewController打开UIViewPicker,如下所示:

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

ChoseOperationViewController是自定义UiViewController类,其中包含UiViewPickerUINavigationBar

的笔尖

我已将“Anuluj”(取消)按钮连接到动作,如下图所示: enter image description here

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

1 个答案:

答案 0 :(得分: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实例被解除分配