0

I'm getting some weird behavior in my UITableViewController.

I've subclassed UITableViewCell and created by own "visited" property within it.

- (void)setVisited:(BOOL)visited animated:(BOOL)animated
{
    [self setVisited:visited];
    ...
}

I set this property when I create the cell in tableView:cellForRowAtIndexPath: (the only place I create it) like below:

if (cell == nil) {
    cell = [[ArticleListViewCell alloc] initWithReuseIdentifier:CellIdentifier art:art index:indexPath.row];
    [cell setVisited:NO animated:NO];
}

Later, in tableView:didSelectRowAtIndexPath:, I set this property to YES:

ArticleListViewCell *cell = (ArticleListViewCell *) [tableView cellForRowAtIndexPath:indexPath];
[cell setVisited:YES animated:NO];

However, when I select a cell and then return to this UITableView, which currently has 10 cells, I find that not only has the cell I selected become "visited", but also another cell has as well. It's hard to explain, but if I select the 1st cell, the 7th also becomes visited, if I select the 2nd, the 8th also becomes visited, and so on. Does anyone know why this is, and how I should go about fixing it?

I've checked this question, but it doesn't seem to help much.

Community
  • 1
  • 1
Hari Ganesan
  • 532
  • 4
  • 18
  • Cells are reused, so that's why you get that result. You need to keep track of the index paths of any visited cells. – rdelmar Feb 19 '14 at 01:11

1 Answers1

2

This is caused by cell reuse. You need to set visited every time, not just when you create the cell.

if (cell == nil) {
    cell = [[ArticleListViewCell alloc] initWithReuseIdentifier:CellIdentifier art:art index:indexPath.row];
}

BOOL visited = ... // value for this indexPath
[cell setVisited:visited animated:NO];

And in your didSelectRow method you need to update some sort of data structure keeping track of which row has been visited. You use this data to set the value properly in the cellForRow method.

Do not use the cell to keep track of state. The cell is a view. Your data source needs to track the state.

rmaddy
  • 314,917
  • 42
  • 532
  • 579
  • Thanks -- I should be keeping the state in a data source; I was mostly just confused as to why the views were changing in that particular way. – Hari Ganesan Feb 19 '14 at 01:15