在uitableview中的resignFirstResponder崩溃

时间:2011-07-03 14:44:49

标签: iphone objective-c uitableview uitextfield

在我的UITableView我有一组包含UITextField的自定义单元格。我发现(困难的方式),显然离开当前视图(通过推动新的视图控制器或解除活动视图('返回'))将使我的应用程序崩溃,当键盘仍然可见时。

要在用户编辑UITextField时隐藏键盘,但视图已更改,我在推送新视图控制器之前添加[self.view endEditing:YES];,并在{{1}中添加viewWillDisappear方法。

现在,我的应用程序只破坏了5个中的1个来隐藏键盘。 Here我可能已经了解了这个原因: 当单元格移出屏幕时,它会被破坏/回收,因此可以在需要时再次出列。这意味着,一旦我的单元格和包含的文本字段移出屏幕,向其发送resignFirstResponder消息(手动或[self.view endEditing:YES];,应用程序将崩溃。这是回溯:

#0  0x012e309b in objc_msgSend ()
#1  0x05956888 in dyld_stub_usleep ()
#2  0x003ff056 in -[UIResponder resignFirstResponder] ()
#3  0x003c697f in -[UITextField resignFirstResponder] ()
#4  0x003c6ab1 in -[UIView(UITextField) endEditing:] ()
#5  0x00012c0a in -[MyController viewWillDisappear:] (self=0x7419e90, _cmd=0x52aa27e, animated=1 '\001') at MyController:121
#6  0x003ee9a2 in -[UINavigationController _startTransition:fromViewController:toViewController:] ()
#7  0x003e932a in -[UINavigationController _startDeferredTransitionIfNeeded] ()
#8  0x003e8fb6 in -[UINavigationController _popViewControllerWithTransition:allowPoppingLast:] ()
#9  0x003e9142 in -[UINavigationController popViewControllerAnimated:] ()
#10 0x003e857a in -[UINavigationController navigationBar:shouldPopItem:] ()
#11 0x00389260 in -[UINavigationBar _popNavigationItemWithTransition:] ()
#12 0x0039261b in -[UINavigationBar _handleMouseUpAtPoint:] ()
#13 0x00354ded in -[UIWindow _sendTouchesForEvent:] ()
#14 0x00335c37 in -[UIApplication sendEvent:] ()
#15 0x0033af2e in _UIApplicationHandleEvent ()
#16 0x01ad5992 in PurpleEventCallback ()
#17 0x0115e944 in __CFRUNLOOP_IS_CALLING_OUT_TO_A_SOURCE1_PERFORM_FUNCTION__ ()
#18 0x010becf7 in __CFRunLoopDoSource1 ()
#19 0x010bbf83 in __CFRunLoopRun ()
#20 0x010bb840 in CFRunLoopRunSpecific ()
#21 0x010bb761 in CFRunLoopRunInMode ()
#22 0x01ad41c4 in GSEventRunModal ()
#23 0x01ad4289 in GSEventRun ()
#24 0x0033ec93 in UIApplicationMain ()
#25 0x00001e18 in main (argc=1, argv=0xbffff0a0) at main.m:24

我现在的问题是,在所有情况下,如何正确隐藏UITextFieldUITableViewCell的键盘? (表格视图消失,新视图控制器被按下,单元格/文本字段被移出屏幕等)

任何帮助都非常感谢,我无法摆脱崩溃!

我包含更多代码:

1)自定义单元类:

#import <UIKit/UIKit.h>

enum Type
{
   tpText = 0,
   tpInteger,
   tpDecimal,
   tpNumber
};

@protocol TextInputCellDelegate <NSObject>
@required
- (void)setNewText:(NSString*)newText forIndex:(NSIndexPath*)index;
@end

@interface TextInputCell : UITableViewCell <UITextFieldDelegate> {
   IBOutlet UILabel* mainText;
   IBOutlet UITextField* textField;
   NSNumberFormatter* numberFormatter;
   int type;
   id <TextInputCellDelegate> delegate;
}

- (void) initDelegateWithType:(int)aType;
- (void) save:(NSString*)text;
- (void) startEditing;

@property (nonatomic, retain) UILabel* mainText;
@property (nonatomic, retain) UITextField* textField;
@property (nonatomic, retain) NSNumberFormatter* numberFormatter;
@property (nonatomic, assign) int type;
@property (nonatomic, assign) id <TextInputCellDelegate> delegate;

@end

自定义单元格的实现:

#import "TextInputCell.h"

@implementation TextInputCell

@synthesize mainText;
@synthesize textField;
@synthesize numberFormatter;
@synthesize type;
@synthesize delegate;

- (void) initDelegateWithType:(int)aType {
   self.type = aType;
   textField.delegate = self;   
}


- (BOOL)textField:(UITextField *)aTextField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string; {

   if (![string length] || type == tpText || (isnumber([string characterAtIndex:0]) && type == tpNumber))
   {
      [self save:[textField.text stringByReplacingCharactersInRange:range withString:string]];

      return YES;
   }

   char c = [string characterAtIndex:0]; 
   BOOL isSep = [string isEqualToString:[numberFormatter decimalSeparator]];
   BOOL isMinus = [string isEqualToString:@"-"];
   NSRange sep;
   sep.location = NSNotFound;
   sep.length = 0;

   if ([aTextField.text length])
      sep = [aTextField.text rangeOfString:[numberFormatter decimalSeparator]];

   if (isMinus)
   {
      // allow '-' only if type is tpNumber and field is empty

      if (type != tpNumber)
         return NO;

      if ([aTextField.text length])
         return NO;

      [self save:[textField.text stringByReplacingCharactersInRange:range withString:string]];
      return YES;
   }

   if (isnumber(c) || ((type == tpDecimal || type == tpNumber) && isSep && sep.location == NSNotFound))
   {
      // allow separator for decimal and number, but only if not in text already

      if (!isSep && sep.location != NSNotFound && type == tpDecimal)
      {
         // round after , (only for decimal type)

         NSString* text = [NSString stringWithFormat:@"%@%@", aTextField.text, string];
         double num = [[numberFormatter numberFromString:text] doubleValue];
         double res = ((int)(num / 0.5)) * 0.5;
         aTextField.text = [numberFormatter stringFromNumber:[NSNumber numberWithDouble:res]];

         [self save:aTextField.text];

         return NO;
      }

      [self save:[NSString stringWithFormat:@"%@%@", aTextField.text, string]];

      return YES;
   }

   [self save:[NSString stringWithFormat:@"%@%@", aTextField.text, string]];

   return NO;
}

- (void) save:(NSString*)text {

   UITableView* view = (UITableView*)[self superview];
   NSIndexPath* index =  [view indexPathForCell:self];

   if (delegate)
      [delegate setNewText:text forIndex:index];
}

- (BOOL)textFieldShouldEndEditing:(UITextField *)field 
{
   NSLog(@"should end");

//   if ([field becomeFirstResponder])
//      [field resignFirstResponder];

   return YES;
}

- (BOOL)textFieldShouldReturn:(UITextField *)field {

   if (type != tpText && [field.text length] == 0)
      field.text = @"0";

   NSLog(@"should return");

//   if ([field becomeFirstResponder])
//      [field resignFirstResponder];

   return YES;
}

- (void) startEditing {

   NSLog(@"should return");

   [self.textField becomeFirstResponder];
}

@end

查看包含其中4个单元格的控制器:

@implementation MailPrefController

@synthesize menuItems;
@synthesize mailTo;
@synthesize mailCc;
@synthesize mailBcc;
@synthesize mailSubject;
@synthesize mailBody;


#pragma mark -
#pragma mark Initialization


- (id)initWithStyle:(UITableViewStyle)style {
    // Override initWithStyle: if you create the controller programmatically and want to perform customization that is not appropriate for viewDidLoad.
    if ((self = [super initWithStyle:UITableViewStyleGrouped])) {
    }
    return self;
}


#pragma mark -
#pragma mark View lifecycle


- (void)viewDidLoad {
    [super viewDidLoad];

   // save button

   UIBarButtonItem* saveButton = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemSave target:self action:@selector(saveMailPrefs)];
   self.navigationItem.rightBarButtonItem = saveButton;
   [saveButton release];

   self.navigationItem.title = NSLocalizedString(@"Mail template", nil);

   // menu items

   self.menuItems = [[NSArray alloc] initWithObjects:NSLocalizedString(@"To:", nil), NSLocalizedString(@"Cc:", nil), NSLocalizedString(@"Bcc:", nil), NSLocalizedString(@"Subject:", nil), NSLocalizedString(@"Body:", nil), nil];
}


- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
}

#pragma mark -
#pragma mark Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    // Return the number of sections.
    return 1;
}


- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    // Return the number of rows in the section.
    return [menuItems count];
}


// Customize the appearance of table view cells.
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {

   if (indexPath.row < 4)
   {
      // title

      TextInputCell* textCell = (TextInputCell*)[tableView dequeueReusableCellWithIdentifier:@"TextInputCell"];

      if (textCell == nil)
      {
         NSArray* nibContents = [[NSBundle mainBundle] loadNibNamed:@"TextInputCell" owner:self options:nil];
         textCell = [nibContents lastObject]; 
         textCell.selectionStyle = UITableViewCellSelectionStyleNone;
         textCell.textField.textColor = [Service uiColor];
         textCell.delegate = self;
         [textCell initDelegateWithType:tpText];
      }

      textCell.mainText.text = [menuItems objectAtIndex:indexPath.row];

      switch (indexPath.row)
      {
         case 0: textCell.textField.text = self.mailTo; break;
         case 1: textCell.textField.text = self.mailCc; break;
         case 2: textCell.textField.text = self.mailBcc; break;
         case 3: textCell.textField.text = self.mailSubject; break;

         default: break;
      }

      return textCell;
   }

   // body text multiline

   TextInputMultilineCell* textMultilineCell = (TextInputMultilineCell*)[tableView dequeueReusableCellWithIdentifier:@"TextInputMultilineCell"];

   if (textMultilineCell == nil)
   {
      NSArray* nibContents = [[NSBundle mainBundle] loadNibNamed:@"TextInputMultilineCell" owner:self options:nil];
      textMultilineCell = [nibContents lastObject]; 
      textMultilineCell.selectionStyle = UITableViewCellSelectionStyleNone;
      textMultilineCell.textView.font = [UIFont systemFontOfSize:12];
      textMultilineCell.textView.textColor = [Service uiColor];
      textMultilineCell.delegate = self;
      [textMultilineCell initDelegate];

      CGRect rect = textMultilineCell.textView.frame;
      rect.size.height *= 2;
      textMultilineCell.textView.frame = rect;
   }

   textMultilineCell.mainText.text = [menuItems objectAtIndex:indexPath.row];
   textMultilineCell.textView.text = self.mailBody;

   return textMultilineCell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {

   switch (indexPath.section)
   {
      case 0:
      {
         // general section

         if (indexPath.row < 4)
         {
            TextInputCell* cell = (TextInputCell*)[[self tableView] cellForRowAtIndexPath:indexPath];            
            [cell startEditing];
         }
      }

      default: break;
   }
}

可以通过单击其中一个单元格UITextField来重现崩溃,将单元格滑出屏幕(不隐藏键盘),然后只关闭表格视图(例如通过导航控制器返回)。

单击单元格时手动打开键盘会导致这种情况吗? (startEditing方法)我执行此操作,因此用户不必点击文本字段,但编辑也会在例如点击细胞textlabel。

5 个答案:

答案 0 :(得分:5)

也许有点晚了,但我遇到了类似的问题。我可以看到僵尸已启用,我的UITextView试图通过滚出视图后重新分配消息(使用textViewDidEndEditing)。 在我的等效TextInputCell的dealloc中,我只是将UITextField委托设置为nil。干得好。

答案 1 :(得分:2)

今天我遇到了类似的问题,当键盘可见时按下UINavigation Back Button导致定期崩溃。我的UITextField包含在UIScrollView中,以便在键盘可见时将其向上滚动。

我正在使用ARC在iOS 5.1下编译我的应用程序,我的解决方案是在dealloc调用中将我的UIScrollView委托设置为nil。

答案 2 :(得分:0)

在解除当前视图之前,只需将resignFirstResponder发送到当前编辑的UITextField(但我认为这应该不是问题)。如果您无权访问它 - 请记住在变量中编辑哪个textField:

- (void)textFieldDidBeginEditing:(UITextField *)textField {
    currentTextField = textField;
}

PS。你能发布什么错误显示Xcode吗?

答案 3 :(得分:0)

就像我说的那样,我怀疑你的问题与resignFirstResponder调用没有直接关系,而是与其他东西直接相关。很可能没有人真正“拥有”所涉及的视图(因为,可能是一个太多的释放调用,或者在某些时候未能保留),因此当进行resign调用时,该对象不存在。

您可以尝试打印应用中各种对象的保留计数(特别是文本视图),看看这些值是否符合您的预期。

答案 4 :(得分:0)

我在针对iOS 5.0构建的应用中看到了这一点。想到两个想法:

  1. 显示键盘时阻止滚动,以确保文本字段不被回收。

  2. 修改resignFirstResponder周围的代码以确保它仍然有效,例如: (注意,我将此添加到我的代码中,但尚未验证是否已解决该错误。我会在测试后立即发布更新)

    -(BOOL) textFieldShouldReturn:(UITextField *) textField {  
        if (textfield && [textField isKindOfClass:[UITextField class]] &&  [textField retainCount] > 0 && [textField isFirstResponder])
        {   
            [textField resignFirstResponder];
        }  
        else
        {
            // how to hide the keyboard?
            // since uitextfield is bad the containing cell (self) may be bad, so cant  
            [self.view endEditing:YES];
            // any suggestions?
        }
    
        return YES; 
     }