我一直试图在重新加载应用程序时保存数据。然而,有些数据无法保存。
my global variable
let defaults = UserDefaults.standard
这是我在AddTaskView上的代码
@IBAction func addTask(_ sender: Any) {
let date = datePicker.date
let dateStr = dateFormatter.string(from: date)
taskArray.append(selectedTask)
dateArray.append(dateStr)
defaults.set(selectedTask, forKey: "task")
defaults.set(dateStr, forKey: "date")
dismiss(animated: true, completion: nil)
}
在我的ViewController中,我有我的viewWillApper
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
defaults.string(forKey: "task")
defaults.string(forKey: "date")
tableView.reloadData()
}
如果我打印从AddTaskView返回的数据,它将在控制台上打印
但数据在重新加载应用程序时消失
tableView.dataSource = self (saved in my viewDidLoad)
这是我的tableView
public func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "taskCell", for: indexPath)
cell.textLabel?.text = "\(indexPath.row + 1). \(taskArray[indexPath.row])"
cell.detailTextLabel?.text = dateArray[indexPath.row]
return cell
}
我做错了什么?
谢谢