iOS: lldb EXC_BAD_ACCESS Custom Cell

2019-08-17 04:11发布

问题:

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *CellIdentifier = @"LibraryListingCell";

    InSeasonCell *cell = (InSeasonCell *)[tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil) {
        [[NSBundle mainBundle] loadNibNamed:@"InSeasonCellView" owner:self options:nil];
        cell = [_cell autorelease];
        _cell = nil;
    }
    if(_dataController!=NULL){
        Product *productAtIndex = [_dataController objectInListAtIndex:indexPath.row];
        // Configure the cell...
        if (productAtIndex.name != nil && productAtIndex.week != nil && productAtIndex.image != nil) {
            cell.name.text = productAtIndex.name;
            cell.week.text = productAtIndex.week;
            cell.image.image = productAtIndex.image;
        }
    }

    return cell;
}

Message ERROR for cell.name.text cell.week.text cell.image.text. Pretty sure it is a memory management error. I have retained and released properly to the best of my knowledge. The application will crash upon launch, sometimes it loads everything fine, but when you scroll it crashes. Any help or pointers about memory management is appreciated.

回答1:

Instead of this:

 if (cell == nil) {
    [[NSBundle mainBundle] loadNibNamed:@"InSeasonCellView" owner:self options:nil];
    cell = [_cell autorelease];
    _cell = nil;
  }

You sent autorelease message and set it to nil, later you are trying to access that released cell.

I think it should be as:

static NSString *CellIdentifier = @"LibraryListingCell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];

if (cell == nil){
    cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier];
}