swiftの勉強のためTableViewを利用したToDoアプリを作っています。
ですが、Simulatorを起動すると特にエラーが出てるわけではないのにSimulatorが落ちて「terminating with uncaught exception of type NSException」というエラーが起こります。
多分UserDefaultsのところが原因だと思っています。
まだ勉強したばかりであまりよくわかっていません。
なので、どなたか原因と改善方法を教えていいただけると助かります。
よろしくお願いします。
swift
1import UIKit 2 3var todoList = [String]() 4 5class ViewController: UIViewController, UITableViewDelegate{ 6 7 @IBOutlet var todoTable: UITableView! 8 9 override func viewDidLoad() { 10 super.viewDidLoad() 11 // Do any additional setup after loading the view, typically from a nib. 12 13 14 if UserDefaults.standard.object(forKey: settingKey) != nil { 15 todoList = UserDefaults.standard.object(forKey: settingKey)! as! [String] 16 } 17 18 } 19 20 override func didReceiveMemoryWarning() { 21 super.didReceiveMemoryWarning() 22 // Dispose of any resources that can be recreated. 23 } 24 25 override func viewDidAppear(_ animated: Bool) { 26 27 todoTable.reloadData() 28 29 } 30 31 func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { 32 33 return todoList.count 34 35 } 36 37 private func tableView(_ tableView: UITableView, cellForRowAtIndexPath indexPath: IndexPath) -> UITableViewCell{ 38 39 let cell = UITableViewCell(style: UITableViewCellStyle.default, reuseIdentifier: "ToDo") 40 41 cell.textLabel!.text = todoList[indexPath.row] 42 43 return cell 44 } 45 46 func tableView(_ tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) { 47 48 if editingStyle == UITableViewCellEditingStyle.delete { 49 50 todoList.remove(at: indexPath.row) 51 52 UserDefaults.standard.setValue(todoList, forKey: settingKey) 53 54 todoTable.reloadData() 55 } 56 } 57 58} 59
swift
1class AddViewController: UIViewController { 2 3 @IBOutlet weak var textField: UITextField! 4 5 6 override func viewDidLoad() { 7 super.viewDidLoad() 8 9 // Do any additional setup after loading the view. 10 } 11 12 override func didReceiveMemoryWarning() { 13 super.didReceiveMemoryWarning() 14 // Dispose of any resources that can be recreated. 15 } 16 17 // キーボード外を押した時にキーボードが閉じる 18 override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) { 19 self.view.endEditing(true) 20 } 21 22 @IBAction func AddButtonClick(_ sender: Any) { 23 24 todoList.append(textField.text!) 25 26 textField.text = "" 27 28 UserDefaults.standard.setValue(todoList, forKey: settingKey) 29 30 for x in todoList { 31 print(x) 32 } 33 34 _ = navigationController?.popViewController(animated: true) 35 } 36 37 func textFieldShouldReturn(textField: UITextField!) -> Bool { 38 39 textField.resignFirstResponder() 40 41 print("OK") 42 43 return true 44 } 45 46} 47
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。
2017/06/29 10:39
2017/06/29 20:41