-1

I have this code that is crashing with error *** Terminating app due to uncaught exception 'NSRangeException', reason: '*** -[NSArray objectAtIndex:]: index 0 beyond bounds for empty array'

at this line:

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    MyObject *myCode = [self.fetchedResultsController objectAtIndexPath:indexPath];
}

I don't see whats wrong here, it is pulling the data from a fetch.

Jon
  • 4,732
  • 6
  • 44
  • 67
  • 4
    You don't think there's something wrong if you're trying to access the first element of an empty array? – Hot Licks Sep 07 '11 at 23:17

1 Answers1

4

The answer is right in your post 'reason: ' ... index 0 beyond bounds for empty array'. Your self.fetchedResultsController is empty now you need to investigate why.

Note: Whenever you modify the underlying data for a table view you need to update the changes by either calling -[UITableView reloadData]; or the beginUpdates and endUpdates methods then adding or removing the correct index paths.

Joe
  • 56,979
  • 9
  • 128
  • 135
  • The crash happens when I click the x (clear) icon in the UISearchBar after already searching. The searching works fine, just crashes when I clear it by pressing the x. – Jon Sep 07 '11 at 20:35
  • Ok so thats a start. When you clear it you probably need to reload the tableView that contains the results you can click on that way the table will be empty and the user can not select a row outside of the bounds of the data. – Joe Sep 07 '11 at 20:36
  • When I click the text in the UISearchBar, then click the x, it works fine. It only crashes when I click the X and not the text itself. – Jon Sep 07 '11 at 20:37
  • Thanks, I have all the code related to the search functions here in this question halfway through, I can't seem to see anything wrong as I am reloading the table. http://stackoverflow.com/questions/7338379/getting-exc-bad-access-crash-with-uisearchbar-method – Jon Sep 07 '11 at 20:38
  • Try implementing the [`UITextFieldDelegate`](http://developer.apple.com/library/ios/#DOCUMENTATION/UIKit/Reference/UITextFieldDelegate_Protocol/UITextFieldDelegate/UITextFieldDelegate.html) method `-(BOOL)textFieldShouldClear:(UITextField*)textField` and try clearing your data, reloading the table, and then return YES. – Joe Sep 07 '11 at 20:42
  • I added this but no luck with it: `-(BOOL)textFieldShouldClear:(UITextField*)textField { mySearchBar.text = @""; [mySearchBar resignFirstResponder]; [self.tableView reloadData]; return YES;}` I don't understand why `- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath` is even being called when I click the x button. – Jon Sep 07 '11 at 20:45
  • Make sure you clear your fetched results. Also start adding logs so you can see what the count is your returning for your tableview etc until you find out where the discrepancy is. – Joe Sep 07 '11 at 21:15