views:

28

answers:

1

I have a table being generated from an array of NSManagedObjects. This works fine until I try to add an extra cell at the top of the table.

Here is what I'm trying at the moment:

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    int menuLength = [mainMenu count] + 1;
    return menuLength;
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {

    // Check for reusable cell
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier: @"UITableViewCell"];


    // If no reusable cell, create one
    if (!cell) {
        cell = [[[UITableViewCell alloc] initWithStyle: UITableViewCellStyleDefault
                                   reuseIdentifier: @"UITableViewCell"] autorelease];
    }

    // Set the text on the cell with the genus name that is at the nth index of generaList
    if ([indexPath row] == 0) {
        [[cell textLabel] setText: @"All"];
    } else {
        NSManagedObject *filter = [mainMenu objectAtIndex: [indexPath row]];
        [[cell textLabel] setText: [filter valueForKey: @"filter_label"]];
    }
    return cell;
}

When I try to scroll through the table, it throws the following exception:

'NSRangeException', reason: '* -[_PFArray objectAtIndex:]: index (9) beyond bounds (9)'

Any help would be much appreciated!

+1  A: 

Try this:

int row = [indexPath row];
if (row == 0) {
    [[cell textLabel] setText: @"All"];
} 
else {
   NSManagedObject *filter = [mainMenu objectAtIndex: row-1];

The important change here is subtracting one from row before putting it into objectAtIndex -- I think your failure to do so is what is giving you the exception, as it looks for the object at index 9 in mainMenu.

The setting up of row as its own variable is a good idea whenever you are using something more than once. And in this case, it might have helped you notice your bug more easily.

William Jockusch
Ah of course!! Thank you very much! :)
henrysoup