我有一个视图控制器,可以UIViewController
打开UIViewPicker
,如下所示:
-(void)operationClicked:(id)sender {
ChoseOperationViewController *picker = [[ChoseOperationViewController alloc] initWithNibName:@"ChoseOperationViewController" bundle:[NSBundle mainBundle]];
[self.view addSubview:picker.view];
[picker animateSlideOut];
}
ChoseOperationViewController是自定义UiViewController类,其中包含UiViewPicker
和UINavigationBar
我已将“Anuluj”(取消)按钮连接到动作,如下图所示:
当我点击按钮时,我得到了-[ChoseOperationViewController performSelector:withObject:withObject:]: message sent to deallocated instance 0x7569fd0
并且没有调用cancelClicked方法。那是为什么?
答案 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
实例被解除分配