NSInternalInconsistencyException when trying to dynamically modify number of rows in UITableView

617 views Asked by At

I am attempting to use insertRowsAtIndexPaths so I can insert a table row. I am getting this error:

*** Terminating app due to uncaught exception 'NSInternalInconsistencyException',      reason: 'Invalid update: invalid number of rows in section 0.  The number of rows contained in an existing section after the update (0) must be equal to the number of rows contained in that section before the update (0), plus or minus the number of rows inserted or deleted from that section (1 inserted, 0 deleted).'

What I am trying to do is to dynamically modify the number of rows in section in my attempt at rectifying the problem:

NSArray *indexPathIndex = [NSArray arrayWithObjects:[NSIndexPath indexPathForRow:0   inSection:0], nil];    
[myTableView beginUpdates];
//***** HERE I AM TRYING TO DYNAMICALLY INCREASE NUMBER OF ROWS
[myTableView numberOfRowsInSection:1];
////////////////////////////////////////////////////////////
[myTableView insertRowsAtIndexPaths:indexPathIndex   withRowAnimation:UITableViewRowAnimationTop];
[myTableView endUpdates];

Initially, my number of rows in section is 0. I try to increase this number in my efforts to address the aforementioned error however the code [myTableView numberOfRowsInSection:1] seems to have no effect.

Could somebody please suggest how I can fix this problem?

Thank you, Victor.

3

There are 3 answers

1
Perception On

You should not be setting the number of rows yourself, the UITableView manages that on its own. Remove the line.

myTableView numberOfRowsInSection:1]; 
0
csano On

Take a look at the UITableViewDataSource protocol, particularly the tableView:numberOfRowsInSection method. This will allow you to dynamically set the number of rows in the section.

1
Sailesh On

A tableView has a datasource that is generally an array, that you can use to fill the cells of the tableView.

- (UITableViewCell*)tableView cellForRowAtIndexPath..... {
    //Dequeueing or alloc-init-ing a cell
    SomeClass *someObject = [someArray objectAtIndex:indexPath.row]; // Something
    // like this, where someArray becomes the source array.
    ...
}

Now in some other part of your code, if you want to dynamically change the contents of the tableView, change the someArray and then change the tableView.

[someArray insertObjectAtIndex:someIndex];
[myTableView insertRowsAtIndexPaths....];  //The indexPath is generally
// consistent with the someIndex.