0

I have created an entity called Medications and the function for adding new data is :

@objc func saveUserSettings() {

    SVProgressHUD.show()

    let name = medicationNameTextField.text
    let dosage = dosageTextField.text
    let frequency = medicationNameTextField.text
    let reminder = dosageTextField.text

    let medication = Medications(context: PersistenceService.context)
    medication.name = name
    medication.dosage = dosage
    medication.frequency = frequency
    medication.reminder = reminder

    PersistenceService.saveContext()
    self.meds.append(medication)

}

How can I delete one of those indexes when pressing the delete button at the table view cell?

func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCell.EditingStyle, forRowAt indexPath: IndexPath) {

    if editingStyle == .delete {

        meds.remove(at: indexPath.row)

        let task = meds[indexPath.row]

        PersistenceService.saveContext()

        self.tableView.reloadData()
    }        

}

Any ideas?

Mahgolsadat Fathi
  • 3,107
  • 4
  • 16
  • 34
  • Don't use `self.tableView.reloadData()`in this case. Use `self.tableView.deleteRows(at: [indexPath], with: .fade)` to get the nice cell animation. – vadian Oct 31 '18 at 21:03

1 Answers1

2

Deleteing from the array here

meds.remove(at: indexPath.row)

doesn't automatically remove it from coreData , you need to use

context.delete(object)

before saving the context see here Swift 3 Core Data Delete Object

Also do it in correct order

let task = meds[indexPath.row]

context.delete(task) // access context anywhere but this statement should run

PersistenceService.saveContext()

meds.remove(at: indexPath.row)
Shehata Gamal
  • 98,760
  • 8
  • 65
  • 87