Search code examples
iosuitableviewnstimerreloaddata

TableView reloadData restarts NSTimer in UITableViewCell


I have a UITableView of custom cells. Each cell has an NSTimer that can be set by the user and started by tapping a button. The timers work except when a new cell is added to the TableView. In the unwind method (coming from creating a new object for a new cell) I have to reload the data in the TableView so that the new cell appears. This however reloads all the cells causing any running timer to restart. Is there a way I can add the cell without restarting the running timers?

EDIT:

I have a ViewController that creates a new object and then back in the FirstViewController.m I have an unwind method that should update the tableView with a row for the new object. Using the reloadData method won't work because it reloads all of the cells. I would like to just add a new cell without reloading the entire tableView.

-(IBAction)unwind:(UIStoryboardSegue *)segue {
    ABCAddItemViewController *source = [segue sourceViewController];
    ABCItem *item = source.object;

    if (item != nil) {
        [self.objectArray addObject:item];

        [self.tableView reloadData];
    }
}

To do this I've tried adding these lines instead of [self.tableView reloadData]:

NSIndexPath *indexPath = [NSIndexPath indexPathForRow:[self.objectArray indexOfObject:item] inSection:0];
[self.tableView insertRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationLeft];

However, the app crashes and I get this message:

'Invalid update: invalid number of rows in section 0. The number of rows contained in an existing section after the update (1) must be equal to the number of rows contained in that section before the update (1), plus or minus the number of rows inserted or deleted from that section (1 inserted, 0 deleted) and plus or minus the number of rows moved into or out of that section (0 moved in, 0 moved out).'

The number of rows in the tableView is determined by [self.objectArray count] in the numberOfRowsInSection: method.


Solution

  • It is not a good idea to add timers to cells because they are reused. They are views. My recommendation is to create some objects which have the text / info you want to display in these UITableViewCells and add the timers to those objects. This way the timer info is not stored in the cells and they will store state