'Delete an instance of an entity in CoreData

first of all, sorry if my english is not good enough, but I'm not a native speaker. However, I'm going to do my best.

Having said this, my question is the next: I have the next structure: An entity Recipie with only one attribute: title, and a relation One(Recipie)->ToMany(Ingredients). Ingredients is an entity with the next attributes: name, done, timer.

And I show the recipies title in a table. The recipies are added by an add button and the title attribute is taken from a text field. I've no problem to show the elements in the table with the following code:

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = UITableViewCell(style: .default, reuseIdentifier: "mycell")
        cell.textLabel?.text = manager.fechRecipies()[indexPath.row].title
        return cell
    }

And the fetchRecipies() code is the next:

func fechRecipies() -> [Recipie]{
    let fetchRequest : NSFetchRequest<Recipie> = Recipie.fetchRequest()
        do {
            let result = try container.viewContext.fetch(fetchRequest)
            return result
        } catch {
            print("Error obtaining recipies is: \(error)")
        }
    
        //If error thrown, empty array returned
        return []
}

But I don't know how to delete a recipie from the table once the cell of the recipie is swiped and deleted. The code that I need is the one that I should insert here:

func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCell.EditingStyle, forRowAt indexPath: IndexPath) {
    if editingStyle == .delete {
        
        //Code missing

        table.deleteRows(at: [indexPath], with: .fade)
    }
        
}

I'm sorry if the question is very long but I didn't want to miss important information. I've been searching in Google how to do this but I haven't found the way to delete only one instance of an entity and all the solutions were to delete all the instances, so it doesn't fit in what I want to do.

Any help is appreciated. Thanks!



Solution 1:[1]

You need a data source array.

Create this on the top level of the class

var recipes = [Recipie]()

In viewDidLoad call

self.recipes = manager.fechRecipies()
self.tableView.reloadData()

Replace cellForRowAt with

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
     let cell = tableView.dequeueReusableCell(withIdentifier: "mycell", for: indexPath)
     cell.textLabel?.text = recipes[indexPath.row].title
     return cell
}

Then you are able to delete the object, you need the NSManagedObjectContext instance here called context

func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCell.EditingStyle, forRowAt indexPath: IndexPath) {
    if editingStyle == .delete {
        let itemToDelete = recipes.remove(at: indexPath.row)
        context.delete(itemToDelete)
        tableView.deleteRows(at: [indexPath], with: .fade)
    }
        
}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 vadian