我正在尝试使用coreData构建待办事项列表,我的目标是在用户尝试单击“添加”按钮而不在文本字段中输入任何文本时出现错误弹出通知。 我目前有弹出通知工作,但一旦我解除通知,然后在文本字段中添加文本,然后单击应用程序崩溃的“添加”按钮。
@IBAction func addBtnTaskPressed(_ sender: Any) {
let context = (UIApplication.shared.delegate as! AppDelegate).persistentContainer.viewContext
let task = Task(context: context)
//have to add an if let here.
if let text = textField.text, !text.isEmpty{
task.name = textField.text
//save data to coredata
(UIApplication.shared.delegate as! AppDelegate).saveContext()
} else {
let alert = UIAlertController(title: "Error:", message: "Cannot Add Empty Task", preferredStyle: UIAlertControllerStyle.alert)
alert.addAction(UIAlertAction(title: "Continue", style: UIAlertActionStyle.default, handler: nil))
self.present(alert, animated: true, completion: nil)
}
}
答案 0 :(得分:0)
我认为你没有正确保存coreData。试试这个(我还没有测试过它)
@IBAction func addBtnTaskPressed(_ sender: Any) {
let appDelegate = UIApplication.shared.delegate as! AppDelegate
let context = appDelegate.managedObjectContext
let entity = NSEntityDescription.entity(forEntityName: "Task", in: context)
let task = NSManagedObject(entity: entity!, insertInto: context) as! Task
//have to add an if let here.
if let text = textField.text, !text.isEmpty{
task.name = textField.text
//save data to coredata
do {
try context.save()
print("saved!")
} catch let error as NSError {
print("Could not save \(error), \(error.userInfo)")
}
} else {
let alert = UIAlertController(title: "Error:", message: "Cannot Add Empty Task", preferredStyle: UIAlertControllerStyle.alert)
alert.addAction(UIAlertAction(title: "Continue", style: UIAlertActionStyle.default, handler: nil))
self.present(alert, animated: true, completion: nil)
}
}