Alon Shlider
Alon Shlider

Reputation: 1308

how to save array of model to core data NSmanagedobject?

I am working with a list of objects that are being added to core data NSManagedobject each time seperately - that works fine.

The issue I am facing when adding the swipe to delete feature, I need to delete the current saved array in core data & save the new complete array, not add them one by one. Here is the code I am using which does not work and I hope someone can point out what I am doing wrong -


func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCell.EditingStyle, forRowAt indexPath: IndexPath) {
        if editingStyle == .delete {
            customers.remove(at: indexPath.row)
            let customersPersistancy = CustomerModel(context: context)
            for customer in customers {
                customersPersistancy.name = customer.name
                customersPersistancy.age = Int16(customer.age)
                customersPersistancy.surname = customer.surname
                customersPersistancy.region = customer.region
                customersPersistancy.gender = customer.gender
            }
            //print(customersPersistancy)
            saveData()
            tableView.reloadData()
        }
    }

func saveData(){
        do {
            try context.save()
            print("data saved successfully")
        } catch {
            print("error saving context, \(error.localizedDescription)")
        }
    }

Not only does that not delete the desired row but it actually duplicates the row multiple times which I don't understand why.

Upvotes: 0

Views: 83

Answers (1)

vadian
vadian

Reputation: 285250

Your code makes no sense. The method tableView(_:commit:forRowAt:) passes the current index path and you have to

  • Remove the item from the data source array
  • Delete the item in the managed object context
  • Delete the row
  • Save the context

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

Upvotes: 1

Related Questions