I have a UITableViewCell subclass which has a property called entryView, in place of the read-only cell.contentView. I thought I was using the table view correctly – remembering that the cells get re-used for every entry, and everything needs to be added every time. Occasionally when scrolling however, the entryView will disappear on a cell. The cell will still be there, but the entryView appears to be removed from superview. Here’s my cellForRowAtIndexPath:
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *CellIdentifier = @"Cell";
JTimelineCell *cell = (JTimelineCell *)[tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[JTimelineCell alloc] initWithStyle:UITableViewCellStyleDefault
reuseIdentifier:CellIdentifier];
}
JTimelineCellContentView *contentView;
Entry *entry = [_fetchedResultsController objectAtIndexPath:indexPath];
if ([self.cellContentCache objectForKey:entry.entryID]) {
contentView = [self.cellContentCache objectForKey:entry.entryID];
contentView.frame = cell.bounds;
[contentView setNeedsDisplay];
}
else {
contentView = [[JTimelineCellContentView alloc] initWithFrame:cell.bounds];
[self.cellContentCache setObject:contentView forKey:entry.entryID];
contentView.time = [NSDate timeStringForTime:entry.creationDate];
contentView.message = entry.message;
[cell setNeedsDisplay];
}
[cell.entryView removeFromSuperview];
cell.entryView = contentView;
[cell addSubview:cell.entryView];
return cell;
}
I believe you posted something similar in a different question. You cannot cache the contentView of a cell. You CAN cache images, strings, numbers, values etc – but in the end, when you get a cell, you need to retrieve the elements that will DISPLAY those values, and then set their values to do so. So you can cache images, strings, CGRects, etc – and then when asked to populate a cell, you can look at your cache, and if valid then get the values you have cached. If the cache is not set, then you need to create them from scratch.
Every time you get a cell for a particular section/row, its different. It maybe have old values in it, or it may be new. You need to set each GUI element for each item. One way to make it easy to find those elements is give each a unique tag, so you can use [cell.contentView viewForTag:xxx] to get the item, then set it.