1

I'm want to delete a cell from table view and core data. When I'm trying to delete cell its delete it from table view but doesn't delete from core data and if update table view it appears again. I tried to in use update table view in my delete action but it doesn't work. Maybe I should try managedObjectContext but it doesn't work for me because I'm getting an error.

    override func viewDidLoad() {
    super.viewDidLoad()
    // Do any additional setup after loading the view.
    let nib = UINib.init(nibName: "CustomTableViewCell", bundle: nil)
    self.tableView.register(nib, forCellReuseIdentifier: "cell")
    let fetchRequest: NSFetchRequest<Person> = Person.fetchRequest()
    do {
    let desserts = try PersistenceServce.context.fetch(fetchRequest)
        self.desserts = desserts
        self.tableView.reloadData()
    } catch {}
}

@IBOutlet weak var tableView: UITableView!
var desserts = [Person]()

@IBAction func onAddTapped() {
    let alert = UIAlertController(title: "Add Goal", message: nil, preferredStyle: .alert)
    alert.addTextField { (dessertTF) in
        dessertTF.placeholder = "Enter Goal"
    }
    let action = UIAlertAction(title: "Add", style: .default) { (_) in
        guard let dessert = alert.textFields?.first?.text else { return }
        print(dessert)

        let person = Person(context: PersistenceServce.context)
        PersistenceServce.saveContext()
        self.desserts.append(person)
        self.tableView.reloadData()
    }
    alert.addAction(action)
    present(alert, animated: true)
}



func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
    tableView.deselectRow(at: indexPath, animated: true)
    performSegue(withIdentifier: "segue", sender: self)
}

}

extension ViewController: UITableViewDataSource {

func numberOfSections(in tableView: UITableView) -> Int {
    return 1
}

func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    return desserts.count
}



func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath)
    let dessert = desserts[indexPath.row]

    return cell
}


func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCell.EditingStyle, forRowAt indexPath: IndexPath) {
    guard editingStyle == .delete else { return }
    desserts.remove(at: indexPath.row)

    tableView.deleteRows(at: [indexPath], with: .automatic)

}
rmaddy
  • 314,917
  • 42
  • 532
  • 579
Alexey
  • 11
  • 2
  • 1
    you have to delete from core data as well. look at this https://stackoverflow.com/questions/38017449/swift-3-core-data-delete-object – channu Jul 01 '19 at 15:19

0 Answers0