todoアプリを作っていて一応求めている動きを実現させたのですがいくつか疑問点が二つあるので質問させていただきました。
アプリの構成はUITextField(インスタンスの名前はtextField)のテキストとUISwitch(インスタンスの名前はisImp)のbooleanの値をボタン(btnAdd)を押すことでcore dataに保存する形でcore dataのentity nameはTask,attributeはnameとisImportantです。
現在は下のようなコードになっています。(ボタンの部分のみ切り出しました。)
@IBAction func btnAdd(_ sender: Any) { if textField.text?.characters.count != 0{ let context = (UIApplication.shared.delegate as! AppDelegate).persistentContainer.viewContext //entityのクラス?を作成 let task = Task(context: context) task.name = textField.text! task.isImportant = isImp.isOn //save the data to coredata (UIApplication.shared.delegate as! AppDelegate).saveContext() navigationController!.popViewController(animated: true) }else{ let nTAlert = UIAlertController(title: "enter your task", message: nil, preferredStyle: .alert) present(nTAlert, animated: true, completion: nil) let okAction = UIAlertAction(title: "OK", style: .cancel, handler: {action -> Void in}) nTAlert.addAction(okAction) } }
textFieldになにも入力されなかった場合enter your taskと表示されるように作りたかったので上のようになりました。
一つ目の疑問点はtextFieldの空白を確認するために上では文字数をカウントしていますがオプショナルバインディングは使えないのでしょうか?
if let jnil = textField.text{...
としたところうまくいきませんでした。
二つ目の疑問点は
@IBAction func btnAdd(_ sender: Any) { let context = (UIApplication.shared.delegate as! AppDelegate).persistentContainer.viewContext //entityのクラス?を作成 let task = Task(context: context) if textField.text?.characters.count != 0{ task.name = textField.text! task.isImportant = isImp.isOn //save the data to coredata (UIApplication.shared.delegate as! AppDelegate).saveContext() navigationController!.popViewController(animated: true) }else{ let nTAlert = UIAlertController(title: "enter your task", message: nil, preferredStyle: .alert) present(nTAlert, animated: true, completion: nil) let okAction = UIAlertAction(title: "OK", style: .cancel, handler: {action -> Void in}) nTAlert.addAction(okAction) } }
とした場合に空白でボタンを押してから文字を入力してボタンをもう一度押すとエラーが出ました。appleの公式サイトで調べるとviewContextのスーパクラスは一つのcontextに一つしか存在できないと書いてあったのでそれが今回のエラーの原因なのでしょうか?ボタンを押して実行された関数は終わったら捨てられてもう一度ボタンを押したらまた新しい関数が作られるからいいかなと思ったんですがこの考えのどこに間違いがあるのか教えて下さい宜しくお願いします。
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。