如何从数据核心Swift 4中删除tableview index.row

时间:2018-10-31 20:47:38

标签: swift core-data core

我创建了一个名为药物的实体,添加新数据的功能是:

@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)

}

在表格视图单元格中按删除按钮时,如何删除这些索引之一?

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()
    }        

}

有什么想法吗?

1 个答案:

答案 0 :(得分:2)

从此处删除数组

meds.remove(at: indexPath.row)

不会自动将其从coreData中删除,您需要使用

context.delete(object)

在保存上下文之前,请参见Swift 3 Core Data Delete Object

也请按照正确的顺序进行操作

let task = meds[indexPath.row]

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

PersistenceService.saveContext()

meds.remove(at: indexPath.row)