title: Deleting an object from a table view with CoreData in Swift 3
body: <p>I'm starting to learn CoreData today and I followed a good tutorial on Ray Wenderlich (<a href="https://www.raywenderlich.com/145809/getting-started-core-data-tutorial" rel="nofollow noreferrer">https://www.raywenderlich.com/145809/getting-started-core-data-tutorial</a>)</p>
  
  <p>The finished project ends with a table view, populated with labels the user enters via an Add button in the nav bar.</p>
  
  <p>I also went ahead and put in a delete function since that wasn't in the tutorial:</p>
  
  <pre><code>override func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath)
  {
      if editingStyle == .delete
      {
  
          guard let appDelegate =
              UIApplication.shared.delegate as? AppDelegate else {
                  return
          }
  
          tableView.beginUpdates()
          companies.remove(at: indexPath.row)
          tableView.deleteRows(at: [indexPath], with: .fade)
          tableView.endUpdates()
  
          appDelegate.saveContext()
      }
  }
  </code></pre>
  
  <p>However when I navigate to a different view controller then return, the deleted object is there again. I have companies initialized as a managed object at the top of the file:</p>
  
  <pre><code>var companies = [NSManagedObject]()
  </code></pre>
  
  <p>And I thought</p>
  
  <pre><code>companies.remove(at: indexPath.row)
  </code></pre>
  
  <p>followed by</p>
  
  <pre><code>appDelegate.saveContext()
  </code></pre>
  
  <p>in the delete function would remove the object from the data source, but like I said it's still there.</p>
  
  <p>How can I delete the object so when I navigate away from the page and come back, its still deleted, but will come back if I restart the app?</p>
  
  <p>EDIT (code that worked for me)</p>
  
  <pre><code>override func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath)
  {
  
      let company = companies[indexPath.row]
  
      if editingStyle == .delete {
          managedContext.delete(company)
  
          do {
              try managedContext.save()
          } catch let error as NSError {
              print("Error While Deleting Note: \(error.userInfo)")
          }
  
      }
  
      // Fetch new data/reload table
      let fetchRequest = NSFetchRequest&lt;NSFetchRequestResult&gt;(entityName: companyEntity)
  
      do {
          companies = try managedContext.fetch(fetchRequest) as! [NSManagedObject]
      } catch let error as NSError {
          print("Error While Fetching Data From DB: \(error.userInfo)")
      }
  
      tableView.reloadData()
  }
  </code></pre>
  
  <p>The above code works so that objects stay deleted if I navigate off the view then come back, however if I relaunch the app, they're still deleted - I'd like the deleted item to return if the app is relaunched.</p>