Search code examples
iosexceptionnsarrayuncaught-exceptionnsrangeexception

Terminating app due to uncaught exception 'NSRangeException', reason: '*** -[__NSArrayM objectAtIndex:]: index 5 beyond bounds [0 .. 4]' in IOS


- (void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath {


    data_web *current_data ;
    current_data = [[structured_question data_webs] objectAtIndex:indexPath.row];
    NSString *is_submited = [NSString stringWithFormat:@"%@",[current_data content_2]];

    if ([is_submited compare:@"Y"] == NSOrderedSame)
        cell.accessoryType = UITableViewCellAccessoryCheckmark;
    else
        cell.accessoryType = UITableViewCellAccessoryDetailDisclosureButton;


}

Above is my script. something is wrong in my script and I cannot find a solution.


Solution

  • In the comment you provided the code for your numberOfRowsInSection method as follows:

    - (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
        if(section == 0)
            return [[testM data_webs] count];
        else
            return [[testS data_webs] count];
    }
    

    However, your willDisplayCell ignores indexPath.section when you access current_data. When the cell from a section that has more rows is displayed, your code will crash.

    You should change your code to something like this:

    NSArray *data_webs;
    // This part mimics your "numberOfRowsInSection'
    if (indexPath.section == 0) {
        data_webs = [testM data_webs];
    } else {
        data_webs = [testS data_webs];
    }
    data_web *current_data ;
    current_data = [data_webs objectAtIndex:indexPath.row];
    

    I do not know what's structured_question in your code was, and why you were using it, but the above should eliminate the crash in the objectAtIndex: method.