I’ve read a few SO posts regarding this issue, but seem to be having issues (hair pulling included of course) adding an additional cell to the top of a UITableView. Here is my code:
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
// self.StringArray has 5 string objects inside
return ([self.stringArray count] + 1);
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = @"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
}
// create hardcoded first row in table
if([indexPath row] == 0)
{
cell.textLabel.text = @"Select me";
}
else
{
// decrement the row to get the correct object from the self.stringArray
int arrayIndex = [indexPath row] - 1;
cell.textLabel.text = [self.stringArray objectAtIndex:arrayIndex];
}
return cell;
}
Everything looks good (obviously something is wrong though if I’m getting exception error), but I can’t seem to eyeball it.
Exception: * Terminating app due to uncaught exception ‘NSRangeException’, reason: ‘* -[__NSArrayM objectAtIndex:]: index 5 beyond bounds [0 .. 4]’
I found the problem. I overlooked the fact that I didn’t account for the other UITableView delegate methods, and I didn’t account for this extra row in the UITableView when setting up the logic for the tableView:canEditRowAtIndexPath method. Here is the code that fixed the problem: