Search code examples
iosswiftuitableviewrowdelete-row

Delete UITableView Rows in View Controller with multiple tableviews (Swift)


I am trying to implement a delete row in one of a tableview in my viewcontroller that contains multiple UITableViews. My arrays are saved with NSUserDefaults. Here is my code but I get the error Index out of range here is also a link for my project if anyone want to test it: https://files.fm/f/wv9uerhn

 func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) {

    if editingStyle == .delete {

    if tableView == ScheduleTableView{

       // Here is my code but it gives me an error, first you need to add a row with the add button

        let defaults = UserDefaults.standard
        var myarray = defaults.stringArray(forKey: "ScheduleArray") ?? [String]()

        print(myarray)
        myarray.remove(at: indexPath.row)
        ScheduleTableView.deleteRows(at: [indexPath], with: .fade)


    }

    if tableView == GoalsTableView{



    }
  }
}

Solution

  • You were actually not saving the array with the deleted record to UserDefaults. Update your code to

    func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) {
    {
            if editingStyle == .delete {
    
            if tableView == ScheduleTableView{
    
               // Here is my code but it gives me an error, first you need to add a row with the add button
    
                let defaults = UserDefaults.standard
                var myarray = defaults.stringArray(forKey: "ScheduleArray") ?? [String]()
    
                print(myarray)
                myarray.remove(at: indexPath.row)
                defaults.set(myarray, forKey: "ScheduleArray")
                ScheduleTableView.deleteRows(at: [indexPath], with: .fade)
    
    
            }
    
            if tableView == GoalsTableView{
    
    
    
            }
        }
      }
    }
    

    Hope this helps. Happy Coding.