Search code examples
iosuitableviewnsnotification

iOS UITableView behaviour broken when not active


My current set up is the following:

Root Tab Bar:

  • Collection view with magazines
  • Bookmarks (with a table view)
  • Others

You can add a bookmark from a magazine in the collection view and also remove it from there.

The behaviour I'm seeing is the following: I start the application, the table view queries the number of sections, number of cells, but not the cellForRowAtIndexPath. I could understand why, as there is no cell in the active view, so no data should be loaded.

When I add a bookmark from the collection view, it adds it to the array (via a notification) and requests the tableview to be reloaded. As there isn't an initial entry, it goes through the motions described above. When I press it again to remove the bookmark the entry is removed from the array. This is where it gets interesting because the first thing the table calls is not the number of sections or rows but the cellForRowAtIndexPath. As the array is empty, the application crashes on a request for data on index 0.

My question is why does the cell creation get called in that order? Is there any way to avoid it?


Solution

  • The reason this was happening is because I was attempting to change something about the table before I reloaded the data.

    [self.tableView setSeparatorStyle: !_helpText.hidden ? UITableViewCellSeparatorStyleNone : UITableViewCellSeparatorStyleSingleLine];
    [self.tableView reloadData];
    

    That was for removing the lines so a message can be displayed. However that update was using old data as reloadData had not been called.

    [self.tableView reloadData];
    [self.tableView setSeparatorStyle: !_helpText.hidden ? UITableViewCellSeparatorStyleNone : UITableViewCellSeparatorStyleSingleLine];
    

    Reversing them fixed the issue.