tags:

views:

29

answers:

1

I have a TableView in which I am adding custom UILabels to the UITableViewCells. The tableView loads fine, but when it tries to dequeue a cell after scrolling the app crashes when it tries to set the text of the UILables. Code follows:

#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;

}

Thanks

+1  A: 

There are two factors at play here:

  1. The default value of a UIView's tag is 0.
  2. The receiver of viewWithTag: is included in the search.

Consequently, your call to [cell.contentView viewWithTag:STYLE_NUMBER_TAG] is returning the content view itself when you really want it to return the UILabel.

The solution is simple. Don't use 0 as a tag.

James Huddleston
James, my man! Thanks for the answer. That was exactly right.
Alpinista
No problem. You're not the first person to get stung by using 0 as a tag. ;) To make your code easier to maintain, consider using an enum starting with 1 to define your tags.
James Huddleston