UITableViewController在tableView中崩溃:cellForRowAtIndexPath:

时间:2010-09-30 22:53:35

标签: iphone

我有一个TableView,我在其中向UITableViewCells添加自定义UILabel。 tableView加载正常,但是当它尝试设置UILables的文本时,在滚动应用程序崩溃时尝试使单元格出列。代码如下:

#define STYLE_NUMBER_TAG 0
#define COLORWAY_TAG 1
#define SIZE_TAG 2
#define QUANTITY_TAG 3

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {

// Get the managedObject
NSManagedObject *managedObject = [fetchedResultsController objectAtIndexPath:indexPath];
OrderLineItem *item = (OrderLineItem *)managedObject;

static NSString *CellIdentifier = @"lineItemCell";

UILabel *styleNumberLabel, *colorwayLabel, *sizeLabel, *quantityLabel;

UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
    cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];

    quantityLabel = [[[UILabel alloc] initWithFrame:CGRectMake(5, 5, 70, 20)] autorelease];
    quantityLabel.tag = QUANTITY_TAG;
    [cell.contentView addSubview:quantityLabel];

    styleNumberLabel = [[[UILabel alloc] initWithFrame:CGRectMake(85, 5, 70, 20)] autorelease];
    styleNumberLabel.tag = STYLE_NUMBER_TAG;
    [cell.contentView addSubview:styleNumberLabel];

    colorwayLabel = [[[UILabel alloc] initWithFrame:CGRectMake(165, 5, 70, 20)] autorelease];
    colorwayLabel.tag = COLORWAY_TAG;
    [cell.contentView addSubview:colorwayLabel];

    sizeLabel = [[[UILabel alloc] initWithFrame:CGRectMake(245, 5, 70, 20)] autorelease];
    sizeLabel.tag = SIZE_TAG;
    [cell.contentView addSubview:sizeLabel];

} else {
    styleNumberLabel = (UILabel *)[cell.contentView viewWithTag:STYLE_NUMBER_TAG];
    colorwayLabel = (UILabel *)[cell.contentView viewWithTag:COLORWAY_TAG];
    sizeLabel = (UILabel *)[cell.contentView viewWithTag:SIZE_TAG];
    quantityLabel = (UILabel *)[cell.contentView viewWithTag:QUANTITY_TAG];
}

// Configure the cell...
styleNumberLabel.text = item.style.styleNumber; //CRASHES HERE when dequeueing
colorwayLabel.text = item.colorway;
sizeLabel.text = item.size;
quantityLabel.text = [item.quantity stringValue];

return cell;

}

由于

1 个答案:

答案 0 :(得分:7)

这里有两个因素:

  1. UIView标签的默认值 是0。
  2. viewWithTag:的接收者是 包含在搜索中。
  3. 因此,当您真正希望它返回[cell.contentView viewWithTag:STYLE_NUMBER_TAG]时,您对UILabel的调用会返回内容视图。

    解决方案很简单。不要使用0作为标记。