Delete from uitableview + write to plist not working

佐手、 提交于 2019-12-02 10:31:37

Try this:

- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath
{
  if (editingStyle == UITableViewCellEditingStyleDelete) {

    [tableView beginUpdates];

    // You are going to modify the table view, but you also need
    // to modify the data source of your table. Since tableData
    // is derived from the content of arrayA, the actual data
    // source is arrayA, so we start with that (also, arrayA is
    // a mutable array, so we are allowed to remove objects from
    // it).
    [arrayA removeObjectAtIndex:indexPath.row];

    // Now we also need to modify tableData. If you don't do this,
    // tableData will report the wrong number of rows when
    // numberOfRowsInSection() is called the next time. This is the
    // direct source of the error that you mention in your question
    // (carefully read the error message, it's really meaningful!).
    // A small problem is that tableData is not a mutable array,
    // so we cannot use removeObjectAtIndex: to modify it (that's
    // probably the source of the error you got with Ilya's answer).
    // The solution is to simply recreate tableData from scratch
    // from the content of arrayA.
    tableData = [arrayA valueForKey:@"Hostname"];

    [arrayA writeToFile:plistPath atomically: TRUE];
    [self.tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationFade];

    [tableView endUpdates];
  }
}

You must change tableData after deleting, whereupon reload table view like this:

[self.tableView reloadSections:[NSIndexSet  indexSetWithIndex:<#(NSUInteger)#>] withRowAnimation:<#(UITableViewRowAnimation)#>];//With animation

or reload all table without animation:

[self.tableView reloadData];

instead of: [tableView beginUpdates];[tableView endUpdates];

Need code:

  - (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {

    if (editingStyle == UITableViewCellEditingStyleDelete) {

    [tableData removeObjectAtIndex:indexPath.row];
[arrayA setValue:tableData ForKey:@"Hostname"];
        [arrayA writeToFile:plistPath atomically: TRUE];
        [self.tableView reloadSections:[NSIndexSet  indexSetWithIndex:indexPath.section] withRowAnimation:UITableViewRowAnimationFade];

    }
    }
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!