当前位置: 代码迷 >> Iphone >> 定制的tableviewcell ( label + UITextField) 会导致程序crash,该如何解决
  详细解决方案

定制的tableviewcell ( label + UITextField) 会导致程序crash,该如何解决

热度:288   发布时间:2016-04-25 05:50:33.0
定制的tableviewcell ( label + UITextField) 会导致程序crash
定制table view cell, 里面包含一个UILabel, 一个 UITextField,当鼠标点击textfield要准备输入的时候,程序就crash, 报告一下信息:[NSObject respondsToSelector]: message sent to deallocated.

code 大致如下:
定制的cell:
ComboCell.h 

@interace ComboCell: UITableViewCell <UITextFieldDelegate>
{
UITextField * textField;
UILabel *name;
}
@property (strong, nonatomic) IBOutlet UITextField * textField;
@property (strong, nonatomic) IBOutlet UILabel * textField;
@end

ComboCell.m
...
-(BOOL) textFieldShouldReturn:(UITextField *) textField
{
 [textField resignFirstResponder];
return YES.
}
还有一个 comboCell.xib, 里面就是在 UITableViewCell里面添加le label and textField, 并且把textField的delegate设定为 combocell.

使用这个cell的文件里主要有下面的东东:

-(void)viewDidLoad

  [super  viewDidLoad];
  
[self.tableview registerNib:[UINibnibWithNibName:@ComboCell"bundle"nil]forCellResuseIdentifier:@ComboCellId"];


...


-(UITableViewCell*)tableView:(UITableView*)tableView cellForRowAtIndexPath:(NSIndexPath *) indexPath
{
   static NSString * cellID = @"ComboCellId";
ComboCell * cell = (ComboCell *)[tableView dequeueReusableCellWithIdentifier:cellId forIndexPath:indexpath];
return cell;
}

我注意到的一个现象是:如果我不把textField的delegate设定为 ComboCell, 就不会出现crash的现象, 似乎也跟我用nib来创建table cell 有关。 

希望高手指点是什么原因导致crash,怎样fix ? 我有很多不同的cell需要定制,我不想把textField的delegate指定为tableview 的controller.想让每一个模块都相对独立。
多谢大侠帮忙!

------解决方案--------------------
你的cell都没有分配内存
------解决方案--------------------
if (cell == nil)
{
     //给CELL分配一个内存并初始化
}
------解决方案--------------------
-(UITableViewCell*)tableView:(UITableView*)tableView cellForRowAtIndexPath:(NSIndexPath *) indexPath
{
   static NSString * cellID = @"ComboCellId";
ComboCell * cell = (ComboCell *)[tableView dequeueReusableCellWithIdentifier:cellId forIndexPath:indexpath];
if(cell == nil)
{
   cell = [ComboCell alloc] init......]; 方法自己视情况而定
}
return cell;
}
  相关解决方案