我在Xcode中创建一个应用程序,我需要在UITableViewController中添加一个名为PeopleTableViewController的人,导航栏中的Add Button用于连接到NewPersonViewController,即UIViewController。
但是当我点击“+”按钮时,它会显示
线程1:发出SIGABRT信号错误。
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.'
以下是Main.Storyboard
的屏幕截图
以下是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
}
}
以下是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)
}
}
答案 0 :(得分:0)
您是否检查过@IBAction
和@IBOutlet
是否已正确绑定到故事板?
'NSUnknownKeyException', reason: '[ setValue:forUndefinedKey:]: this class is not key value coding-compliant for the key savePerson.'
感觉@IBAction
或IBOutlet
未正确绑定,或者您没有为故事板中的视图控制器正确设置类。在我看来,它试图访问方法savePerson
,但无法在绑定类中找到它。