Getting an "index 0 out of bounds for an empty array" error on a non-empty array

I have this code to add a row to a table view in the controller of the root view of my application:

NSIndexPath *indexPath = [NSIndexPath indexPathForRow:0 inSection:0]; NSArray *myArray = [NSArray arrayWithObject:indexPath]; NSLog(@"count:%d", [myArray count]); [self.tableView insertRowsAtIndexPaths:myArray withRowAnimation:UITableViewRowAnimationFade]; [self.tableView scrollToRowAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:0] atScrollPosition:UITableViewScrollPositionTop animated:YES]; 

When it starts with the simulator, I get this output:

quantity: 1
* Application termination due to an uncaught exception "NSRangeException", reason: "* - [NSMutableArray objectAtIndex:]: index 0 outside for an empty array

This happens on the line [self.tableView insertRowsAtIndexPaths:myArray withRowAnimation:UITableViewRowAnimationFade]; but the NSLog statement shows that an NSArray called myArray is not empty. Am I missing something? Has anyone ever come across this before?

+4
source share
2 answers

In the line before the log statement, you create a new array that is valid only within this method. The array that you use for the table data source methods is different, therefore the number of objects in this array does not matter at all, even if it has (as I suspect) the same name.

+1
source

A call to the insertRowsAtIndexPaths function calls the UITableViewController delegate / data source method calls. This means that a UITableView can retrieve data for a new row. You need to insert data into your data model and make sure that numberOfRowsInSection returns a new incremented value.

The NSRangeException error refers to any NSMutableArray that you use to store your data for table rows, not an array of index paths.

0
source

All Articles