Delete Data from Coredata Swift

后端 未结 8 1255
你的背包
你的背包 2020-12-05 00:51

In my tableViewController I have the following. And I am trying to get delete an item to work.

var myData: Array = []

override func tableV         


        
8条回答
  •  遥遥无期
    2020-12-05 01:26

    Swift 3.0

    Below is the code to delete item and to reload the data.

    func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) {
    
         let noteEntity = "Note" //Entity Name
    
         let managedContext = (UIApplication.shared.delegate as! AppDelegate).persistentContainer.viewContext
    
         let note = notes[indexPath.row]
    
         if editingStyle == .delete {
            managedContext.delete(note)
    
            do {
                try managedContext.save()
            } catch let error as NSError {
                print("Error While Deleting Note: \(error.userInfo)")
            }
    
         }
    
        //Code to Fetch New Data From The DB and Reload Table.
        let fetchRequest = NSFetchRequest(entityName: noteEntity)
    
        do {
            notes = try managedContext.fetch(fetchRequest) as! [Note]
        } catch let error as NSError {
            print("Error While Fetching Data From DB: \(error.userInfo)")
        }
        noteTableView.reloadData()
    }
    

提交回复
热议问题