views:

112

answers:

2

Hi,

I am new in iPhone development. I am developing an application that fetches a value from a database and displays it in a table view. I want to delete table rows one by one but the rows do not delete and the application crashes.

Here is my row deletion code:

- (void)tableView:(UITableView *)tv commitEditingStyle:(UITableViewCellEditingStyle)editingStyle 
                                     forRowAtIndexPath:(NSIndexPath *)indexPath 
{    
if(editingStyle == UITableViewCellEditingStyleDelete) {
    SanjeevKapoorAppDelegate *appDelegate =(SanjeevKapoorAppDelegate *)[[UIApplication sharedApplication] delegate];
    list *animal =[appDelegate.list1 objectAtIndex:indexPath.row];
    [appDelegate deleteCoffee];      
    [self.tableView reloadData];
    //Delete the object from the table.
    [self.tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationFade];
}

I also delete all rows with this action:

-(IBAction)deletebtn:(id)sender{
    SanjeevKapoorAppDelegate *appDelegate =(SanjeevKapoorAppDelegate *)[[UIApplication sharedApplication] delegate];
       [appDelegate deleteCoffee]; 
       [self.tableView reloadData];
}

How do I properly implement delete in an UITableView?

A: 

You need to change:

[self.tableView reloadData];
//Delete the object from the table.
[self.tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationFade];

to just:

[self.tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationFade];

You are crashing because you're changing your data model to delete the row, then reloading the table such that the row no longer exist then telling the table to delete the non-existant row.

You don't have to call reload data in this instance because the table has already altered itself visually. You only call reload when a change in the data model forces a change in the table not when a table itself changes the data model.

TechZen
A: 

Try wrapping the call to deleteRows in beginUpdates and endUpdates:

[self.tableView beginUpdates];
[self.tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationFade];
[appDelegate deleteCoffee];      
[self.tableView endUpdates];

I assume deleteCoffee affects how the table is populated. That must go between the update wrappers.

Or you can use reloadData without the other calls:

[appDelegate deleteCoffee];      
[self.tableView reloadData];
drawnonward