I have two UITextFields and want to save the Input in Core Data. If the TextField is empty there should be an Alert like "Please insert value".
I try to do this:
@IBAction func buttonSave(_ sender: AnyObject) {
let db:DB = NSEntityDescription.insertNewObject(forEntityName: "DB", into: DatabaseController.persistentContainer.viewContext) as! DB
if timeFextField.text == "" {
let dateAlert = UIAlertController(title: "Missung Value", message: "Please insert a date.", preferredStyle: UIAlertControllerStyle.alert)
let okAction = UIAlertAction(title: "OK", style: .default){(action: UIAlertAction) in print("OK")
}
dateAlert.addAction(okAction)
self.present(dateAlert, animated: true, completion: nil)
} else {
if labelTypNumber.text == "" {
let typeAlert = UIAlertController(title: "Missung Value", message: "Please select a type.", preferredStyle: UIAlertControllerStyle.alert)
let okAction = UIAlertAction(title: "OK", style: .default){(action: UIAlertAction) in print("OK")
}
typeAlert.addAction(okAction)
self.present(typeAlert, animated: true, completion: nil)
}
else {
db.time = NSDate()
db.date = timeFextField.text!
db.typ = Double(labelTypNumber.text!)!
db.color = colorTextField.text!
db.notes = notesTextField.text!
db.weather = wetterTextField.text!
if mediSegment.selectedSegmentIndex == 0 {
db.medi = mediTextField.text!
} else {
db.medi = "0"
}
if mediSegment.selectedSegmentIndex == 1 {
db.medi2 = mediTextField.text!
} else {
db.medi2 = "0"
}
DatabaseController.saveContext()
navigationController!.popViewController(animated: true)
}
}
}
Now when the UITextField is empty, I get an UIAlert, but when I load the Data from Cora Data, the App crashes.
"fatal error: unexpectedly found nil while unwrapping an Optional value (lldb) "
It looks like, that the values are stored in Core Data even though the alert is showing. Have anyone an idea to fix this problem?
Thanks, many greetings.
Aucun commentaire:
Enregistrer un commentaire