我使用下面的代码将文本字段添加到每个 tableview 单元格,
- (UITableViewCell *)tableView:(UITableView *)tableView
cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
NSInteger row=[indexPath row];
static NSString *SimpleTableIdentifier1 = @"CellTableIdentifier";
//if I change the code to [NSString *SimpleTableIdentifier1 =NSString stringWithFormat:@"CellTableIdentifier%d",row]; everything is fine
UITableViewCell *cell=[tableView dequeueReusableCellWithIdentifier: SimpleTableIdentifier1 ];
if (cell == nil){
CGRect cellframe=CGRectMake(0, 0, 200, 60);
cell=[[[UITableViewCell alloc] initWithFrame: cellframe reuseIdentifier:SimpleTableIdentifier1] autorelease];
UITextField * textfieldCell =[[UITextField alloc]init];
textfieldCell.frame = CGRectMake(100.0f,20.0f,60.0f,26.0f) ;
[textfieldCell setDelegate:self];
[textfieldCell setTag:40000+row];//add row value here for later use,
[cell.contentView addSubview:textfieldCell];
[textfieldCell release];
}
UITextField *textfieldCell ;
textfieldCell =(UITextField*)[cell.contentView viewWithTag:40000+row];
textfieldCell.text=[ NSMutableString stringWithString:@"aaa1"];
DebugLog(@"---------%@",textfieldCell.text);
return cell;
}
textfieldCell.text 有时会显示 null 而不是我对 'aaa1' 的期望值
这意味着代码行位于:
textfieldCell =(UITextField*)[cell.contentView viewWithTag:40000+row];
有时返回nil,尝试修复这个困惑的结果但失败
欢迎您的评论
这个dequeueReusableCellWithIdentifier
UITableViewCell *cell=[tableView dequeueReusableCellWithIdentifier: SimpleTableIdentifier1 ];
返回一个非零单元格 Docs
This method dequeues an existing cell if one is available or creates a new one using the class or nib file you previously registered. If no cell is available for reuse and you did not register a class or nib file, this method returns nil
可能有一个带有不同标签的 textField 导致 nil
UITextField *textfieldCell ;
因为这两行
// here rhs may be nil
textfieldCell =(UITextField*)[cell.contentView viewWithTag:40000+row];
textfieldCell.text=[ NSMutableString stringWithString:@"aaa1"];
对 nil textfield 没有影响,而且令人震惊的是你仍然在这里使用 MRC(手动引用计数)
[textfieldCell release];
请更新到 ARC(自动引用计数),这将消除您对内存管理问题的担忧
Tôi là một lập trình viên xuất sắc, rất giỏi!