gpt4 book ai didi

ios - if let 语句错误

转载 作者:行者123 更新时间:2023-11-30 12:45:57 25 4
gpt4 key购买 nike

我正在尝试使用 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)
}

}

最佳答案

我认为您没有正确保存 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)
}
}

关于ios - if let 语句错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41645488/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com