Fatal Error saving to CoreData from TableView

Hello:


NOTE: I found the error before this could be posted. The entity name in the code was missing an "s"!!!


I am using CoreData with TableView in my application. I have a tutorial that I am using to learn the process but when I run the code it is producing a fatal error. THE APP CRASHES WHEN I CLICK THE SAVE BUTTON.


Please look at the code and the error location to help me in correcting error in the code.


Fatal error: Unexpectedly found nil while unwrapping an Optional value

2019-05-21 17:00:07.684361-0400 CoreDataTableView[5820:1399382] Fatal error: Unexpectedly found nil while unwrapping an Optional value:


// ViewController.swift

// CoreDataTableView

//

// Created by W Lionel Williams on 5/20/19.

// Copyright © 2019 W Lionel Williams. All rights reserved.

//


import UIKit

import CoreData


class ViewController: UIViewController {



var people: [NSManagedObject] = []


@IBOutlet weak var tableView: UITableView!


override func viewDidLoad() {

super.viewDidLoad()

title = "The List"

tableView.register(UITableViewCell.self,

forCellReuseIdentifier: "Cell")


}

@IBAction func addName(_ sender: UIBarButtonItem) {

let alert = UIAlertController(title: "New Name",

message: "Add a new name",

preferredStyle: .alert)

let saveAction = UIAlertAction(title: "Save", style: .default) {

[unowned self] action in

guard let textField = alert.textFields?.first,

let nameToSave = textField.text else {

return

}

self.save(name: nameToSave)

self.tableView.reloadData()

}

let cancelAction = UIAlertAction(title: "Cancel",

style: .cancel)

alert.addTextField()

alert.addAction(saveAction)

alert.addAction(cancelAction)

present(alert, animated: true)

}

func save(name: String) {

guard let appDelegate =

UIApplication.shared.delegate as? AppDelegate else {

return

}

let managedContext =

appDelegate.persistentContainer.viewContext

let entity =

NSEntityDescription.entity(forEntityName: "Person",

in: managedContext)! //Fatal Error Here:

let person = NSManagedObject(entity: entity,

insertInto: managedContext)

person.setValue(name, forKeyPath: "name")

do {

try managedContext.save()

people.append(person)

} catch let error as NSError {

print("Could not save. \(error), \(error.userInfo)")

}

}

}


// MARK: - UITableViewDataSource

extension ViewController: UITableViewDataSource {

func tableView(_ tableView: UITableView,

numberOfRowsInSection section: Int) -> Int {

return people.count

}


func tableView(_ tableView: UITableView,

cellForRowAt indexPath: IndexPath)

-> UITableViewCell {

let person = people[indexPath.row]

let cell =

tableView.dequeueReusableCell(withIdentifier: "Cell",

for: indexPath)

cell.textLabel?.text =

person.value(forKeyPath: "name") as? String

return cell

}

}