EXC_BAD_ACCESS
我的视图控制器中的以下代码导致touch.view
调用:
- (BOOL)handleSingleTap:(UITapGestureRecognizer *)recognizer shouldReceiveTouch:(UITouch *)touch {
if ([touch.view isKindOfClass:[UIControl class]]) { // <<<< EXC_BAD_ACCESS HERE
// we touched a button, slider, or other UIControl
return NO; // ignore the touch
}
[self.view endEditing:YES]; // dismiss the keyboard
return YES; // handle the touch
}
touch
似乎是僵尸。具体来说,touch
设置为一个地址,调试器认为这是一个UITouch
指针,但它没有任何属性:
这在 iOS 4.x 中没有发生。所以 iOS 6 错误还是我的错?
手势识别器设置如下(在 ViewController 中):
UITapGestureRecognizer *tapRecognizer = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(handleSingleTap:shouldReceiveTouch:)];
[tapRecognizer setDelegate:self];
[tapRecognizer setNumberOfTapsRequired:1];
[tapRecognizer setNumberOfTouchesRequired:1];
tapRecognizer.cancelsTouchesInView = NO;
[self.view addGestureRecognizer:tapRecognizer];
[tapRecognizer release];
更新/解决方案:
感谢 Rob 指出我的用户错误。不仅如此,我实际上并不需要 TapRecognizer,因为我只想知道发生了触摸。
这是在 UIControl 以外的任何位置通过触摸关闭屏幕键盘的正确代码:
在 ViewController 中viewDidLoad
:
UIGestureRecognizer *myRecognizer = [[UIGestureRecognizer alloc] init];
[myRecognizer setDelegate:self];
myRecognizer.cancelsTouchesInView = NO;
[self.view addGestureRecognizer:myRecognizer];
[myRecognizer release];
和:
- (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldReceiveTouch:(UITouch *)touch {
if ([touch.view isKindOfClass:[UIControl class]]) {
// we touched a button, slider, or other UIControl
return NO; // ignore the touch
}
[self.view endEditing:YES]; // dismiss the keyboard
return YES; // handle the touch
}