4

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?

2 Answers 2

1

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.

Sign up to request clarification or add additional context in comments.

1 Comment

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.
0

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.

1 Comment

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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.