I've got a UITextField on UITableViewCell, and a button on another cell.
I click on UITextField (keyboard appears).
UITextField has the following method called:
- (BOOL)textFieldShouldBeginEditing:(UITextField *)textField {
NSLog(@"yes, it's being called");
owner.activeTextField = textField;
return YES;
};
Where owner.activeTextField is a (retain, nonatomic) property.
The problem When the keyboard is visible I scroll the cell out of the view. I then click a button that is on a different cell. The button calls:
[owner.activeTextField resignFirstResponder]
And that causes EXC_BAD_ACCESS.
Any idea? The cell is most definitely in the memory. My guess is that once it disappears it is removed from the view and one of it's properties (parent view?) becomes nil and that causes the said error..
Am I right?
TL;DR; How can I remove the 开发者_运维问答keyboard (resign first responder) when UITextField is removed from the view?
Sometimes the problem can be another level deep... Check and make sure that the next object in the responder chain (the one that's subsequently receiving the becomeFirstResponder message) isn't garbage. Just a thought.
Have you checked owner.activeTextField
to see if it has been deallocated / set to nil? Not sure if that would call a EXC_BAD_ACCESS
but worth a try.
Also do you have any calls to NSNotificationCenter
? I was struggling with something similar today which was causing an EXC_BAD_ACCESS
on becomeFirstResponder
, which was due to me calling [[NSNotificationCenter defaultCenter] removeObserver:keyboardObserver];
on the incorrect delegate.
A bit old, but since I just had the same problem with a legacy manual reference counting app, I'll give it a try. Note: this problem shouldn't happen with ARC anymore (and if it does, my solution most definitely doesn't fit there...).
What seems to happen is that:
- the textfield is saved into the cell and is (possibly over)retained
- when you scroll the cell with the textfield, the cell get's recycled (which is good), but the textfield is not (which is why the textfield is still in memory when the bug happens)
- at that point, dismissing the keyboard correctly resign the first responder for the textfield, but as the call travels down the view hierarchy, it hits the cell, which is not in memory anymore.
a simple (and imo elegant) solution for the problem would be to
- fix the over retention of uitextfield if any
- subclass UITextField to resign first responder status before being deallocated
a single method,like this:
- (void) dealloc {
[self resignFirstResponder];
[super dealloc];
}
would be required, which will have the side-effect benefit of removing the keyboard as soon as the cell gets out of view.
Another solution (which is the one I chose, for various reasons) would be to manually retain and recycle the cell with the textfield until the table is deallocated.
i'm sure you already solved your problem, but I hope this will help someone else...
精彩评论