I’ve a problem deleting a row from a table view. Here is the code that is called when the button on the row is pressed. I’ve used the tag parameter to tell me which row I’m dealing with, which is why I call reloadTableView at the end to reapply all the tags. If I update the visible rows I was having crashes. So I must be doing something wrong here?
- (void) deleteLineItem:(id)sender
{
UIButton *deleteBtn = sender; // Need to get tag (which was set to table row)
NSIndexPath *indexPath = [NSIndexPath indexPathForRow:(deleteBtn.tag/3) inSection:0];
NSLog(@"Removed entry at %d, with tag %d", indexPath.row, deleteBtn.tag);
[self.productItems removeObjectAtIndex:indexPath.row];
[self.tableview beginUpdates];
[self.tableview deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationRight];
[self.tableview endUpdates];
// Hack to keep table animation ok as we have to do it after the row delete above
[self performSelector:@selector(reloadTableview) withObject:nil afterDelay:0.35];
}
In this case I have two rows in the table.
The datasource is as follows:
Printing description of self->productItems:
(__NSArrayM *) productItems = 0x084fa3b0 @"2 objects"
The indexPath is as follows:
Printing description of indexPath:
<NSIndexPath 0x1069bff0> 2 indexes [0, 1]
When the endUpdates metod is called I get the following crash in the console
2012-10-17 17:04:33.424 myAppname[5782:15203] *** Terminating app due to uncaught exception 'NSRangeException', reason: '*** -[__NSArrayM objectAtIndex:]: index 1 beyond bounds [0 .. 0]'
*** First throw call stack:
(0x1bf0022 0x1918cd6 0x1bdcd88 0xa5553 0xa576b 0x925420 0x963284 0x9633d0 0x925219 0x8fd4f2 0x8fa4c3 0x9050b7 0x9050e5 0xa6ae1 0x1bf1e99 0x87814e 0x8780e6 0x91eade 0x91efa7 0x91e266 0xb39a1a 0x1bc499e 0x1b5b640 0x1b274c6 0x1b26d84 0x1b26c9b 0x25007d8 0x250088a 0x875626 0x1f2ba 0x2ba5)
terminate called throwing an exception(lldb)
I have no idea why is causing a problem.
The code does not look very robust. Seems like you have set the
deleteBtn.tagto a bad value (between 3 and 5, to be more precise) where you had only one cell. Just a guess.A more robust technique for such tasks, which I use, is to implement the IBAction in my
UITableViewCellsubclass and then propagate the request to the controller via delegation and the cell itself as an argument. In the controller then I retrieve the indexPath viaThis way I avoid such hacks.