Sign up ×
Stack Overflow is a community of 4.7 million programmers, just like you, helping each other. Join them; it only takes a minute:

I have this code to add a row to a table view in the root view controller 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 is run with the simulator I get this output:

count:1
* Terminating app due to uncaught exception 'NSRangeException', reason: '* -[NSMutableArray objectAtIndex:]: index 0 beyond bounds for empty array'

This is occurring at the [self.tableView insertRowsAtIndexPaths:myArray withRowAnimation:UITableViewRowAnimationFade]; line, but the NSLog statement shows that the NSArray called myArray is not empty. Am I missing something? Has anyone ever encountered this before?

share|improve this question

In the line before the log statement, you're creating a new array that's only valid in the scope of this method. The array you're using for the table view's data source methods is a different one, so the number of objects in this array doesn't matter at all, even if it has (as I suspect) the same name.

share|improve this answer
    
Yes. I see what you mean, thanks to you both for pointing that out. However, I still have the same issue. The NSMutableArray that I'm storing the data for table rows in, is an iVar called eventsArray. When I change the NSLog statement to NSLog(@"Count:%d", [self.eventsArray count]); I get 14 as the count. Still not an empty array. Any ideas? --Thanks for the help. I really appreciate it. – axl Oct 1 '11 at 18:19

Calling insertRowsAtIndexPaths triggers your UITableViewController delegate/datasource methods to be called. This is so that the UITableView can obtain the data for the new row. You need to insert data into your data model and make sure numberOfRowsInSection is returning the new increased value.

The NSRangeException error is referring to whatever NSMutableArray you are using to store your data for table rows rather than the array of index paths.

share|improve this answer
    
Put break points on all your delegate/datasource methods and then step through the insertRowsAtIndexPaths line. See where you end up and try to narrow down exactly where the exception is being thrown. – Robin Summerhill Oct 1 '11 at 20:43

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.