开发者

iPhone: Crash When Deleting UITableView Rows

开发者 https://www.devze.com 2022-12-26 08:47 出处:网络
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

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?


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.


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];
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号