Kets Kets - 3 months ago 8
Objective-C Question

UITableView BeginUpdates

I'm having some issues with my beginupdates and endupdates from my UITableView. I want to use this functions to animate my tableview instead of using reloadData that i was using till now. It always give a problem when i do it with BeginUpdates and complains about this:

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


So there is a problem with my numberOfRowInSection:

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
int returnInt;

if (section == 0) {
if ([self datePickerIsShown]){
returnInt = 3;
}else{
returnInt = 2;
}
}else if([[[[self theNewGame] _dobbelstenen] objectAtIndex:section - 1] diceSoort] == ENUMOgen){
returnInt = 1;
}else{
returnInt = [[[[[self theNewGame] _dobbelstenen] objectAtIndex:section - 1.0] optiesDobbelsteen] count] + 1.0;
}

return returnInt;
}


And i'm calling it on this way:

if (indexPath.section == 0 && indexPath.row == 1) {
self.datePickerIsShown = ! self.datePickerIsShown;
[tableView beginUpdates];
[tableView endUpdates];
}


What's the problem?

Kind regards

Answer

You are changing the number of rows in the table view data source from 2 to 3.

if ([self datePickerIsShown]) {
    returnInt = 3;
} else {
    returnInt = 2;
}

You must update the table view so the table view and the table view data source agree on the number of rows.

if (indexPath.section == 0 && indexPath.row == 1) {
    self.datePickerIsShown = ! self.datePickerIsShown;
    [tableView beginUpdates];
    if ([self datePickerIsShown])
        [tableView insertRowsAtIndexPaths:@[[NSIndexPath indexPathForRow:2 inSection:0]]
                         withRowAnimation:UITableViewRowAnimationAutomatic];
    else
        [tableView deleteRowsAtIndexPaths:@[[NSIndexPath indexPathForRow:2 inSection:0]]
                         withRowAnimation:UITableViewRowAnimationAutomatic];
    [tableView endUpdates];
}

NOTE: Because you only have 1 change to your table view, you don't need begin and end updates. You can just call the 1 insert or delete that you need.

if (indexPath.section == 0 && indexPath.row == 1) {
    self.datePickerIsShown = ! self.datePickerIsShown;
    if ([self datePickerIsShown])
        [tableView insertRowsAtIndexPaths:@[[NSIndexPath indexPathForRow:2 inSection:0]]
                         withRowAnimation:UITableViewRowAnimationAutomatic];
    else
        [tableView deleteRowsAtIndexPaths:@[[NSIndexPath indexPathForRow:2 inSection:0]]
                         withRowAnimation:UITableViewRowAnimationAutomatic];
}