I am creating an application in Xcode where I need to add people in a UITableViewController with a name PeopleTableViewController and an Add Button in navigation bar is used to connect to NewPersonViewController i.e. is UIViewController.
But when I click on the "+" button it shows
Thread 1: signal SIGABRT error.
Terminating app due to uncaught exception 'NSUnknownKeyException',
reason: '[<Draft3.NewPersonViewController 0x7f9148636650>
setValue:forUndefinedKey:]: this class is not key value
coding-compliant for the key savePerson.'
Following is the screenshot for Main.Storyboard
Following is the code for NewPersonViewController:
import UIKit
class NewPersonViewController: UIViewController {
@IBOutlet weak var personNameTextField: UITextField!
override func viewDidLoad() {
super.viewDidLoad()
personNameTextField.delegate = self as? UITextFieldDelegate
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
personNameTextField.resignFirstResponder()
}
@IBAction func savePerson(_ sender: UIBarButtonItem) {
let person = People(title: personNameTextField.text ?? "")
do {
try person?.managedObjectContext?.save()
self.navigationController?.popViewController(animated: true)
} catch {
print("Could not save the person's name")
}
}
}
extension NewPersonViewController: UITextFieldDelegate {
func textFieldShouldReturn(_ textField: UITextField) -> Bool {
textField.resignFirstResponder()
return true
}
}
Following is the code for PeopleTableViewController:
import UIKit
import CoreData
class PeopleTableViewController: UITableViewController {
@IBOutlet weak var peopleTableView: UITableView!
var people: [People] = []
override func viewDidLoad() {
super.viewDidLoad()
// Uncomment the following line to preserve selection between presentations
// self.clearsSelectionOnViewWillAppear = false
// Uncomment the following line to display an Edit button in the navigation bar for this view controller.
// self.navigationItem.rightBarButtonItem = self.editButtonItem
}
//ViewWillAppear allows us to fetch all the data in the backend and help us display to the user
override func viewWillAppear(_ animated: Bool) {
guard let appDelegate = UIApplication.shared.delegate as? AppDelegate else {
return
}
let managedContext = appDelegate.persistentContainer.viewContext
let fetchRequest: NSFetchRequest<People> = People.fetchRequest()
do {
people = try managedContext.fetch(fetchRequest)
peopleTableView.reloadData()
} catch {
print("Could not fetch")
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
@IBAction func addButtonPressed(_ sender: UIBarButtonItem) {
performSegue(withIdentifier: "addPeople", sender: self)
}
}