Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Keeping a placeholder cell in a UITableView

I have a UITableView that I never want to fall below 1 cell: It's a directory readout, and if there's no files in the directory, it has a single cell that says "No Files". (In edit mode, there's a bonus cell to Create a File, so edit mode never falls below two cells.)

It's probably just lack of sleep keeping me from thinking my way out of a paper bag right now, but I keep tripping up on errors like this:

*** Terminating app due to uncaught exception 
'NSInternalInconsistencyException', reason: 'Invalid update: 
invalid number of sections.  The number of sections contained 
in the table view after the update (2) must be equal to 
the number of sections contained in the table view before 
the update (2), plus or minus the number of sections inserted 
or deleted (1 inserted, 0 deleted).'

This is happening as I'm preemptively adding the "No Files" placeholder before deleting the last file. There's a like crash if I delete the last file cell before adding the placeholder. Either way, the cell count gets out of sync with the return from numberOfRowsInSection, and that triggers a crash.

Surely there's a design pattern for this situation. Clue me in?

like image 831
baudot Avatar asked Feb 26 '23 11:02

baudot


1 Answers

Do something along the lines shown in the code snippet below:

  • first delete the data for the row from the array
  • if array items has not dropped to zero then delete row from table
  • if array items has dropped to zero then reload table - note: your code should now provide 1 for number of rows and configure the cell for row 0 to show "No Files" when the tableview delegate methods are called.
 
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {

    if (editingStyle == UITableViewCellEditingStyleDelete) {
        // First delete the row from the data source
        [self deleteTableData: indexPath.row];  // method that deletes data from 
        if ([self.tableDataArray count] != 0) {
            [tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationFade];
        } else {
            [self.tableView reloadData];
        }

    }   
}
like image 68
jamihash Avatar answered Mar 08 '23 16:03

jamihash