Delete from uitableview + write to plist not working

后端 未结 2 535
无人共我
无人共我 2021-01-26 00:51

i want to delete from uitableview and make it write to my plist. i\'m pretty new to this objective-c iOS coding, so forgive me for mistakes

Right now with my code it cra

相关标签:
2条回答
  • 2021-01-26 01:08

    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];
      }
    }
    
    0 讨论(0)
  • 2021-01-26 01:18

    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];
    
        }
        }
    
    0 讨论(0)
提交回复
热议问题