如何解决移除后台后TODO List应用已删除条目恢复的问题?
问题分析
你的TODO List应用删除条目后,仅修改了内存中的items数组,没有将更新后的数组同步保存到UserDefaults。按Home键后台运行时,内存数据未被清空,功能表现正常;但将应用从后台移除后,内存数据被销毁,重启时会从UserDefaults读取删除前的旧数据,导致已删除的条目重新出现。
修复方案
修改删除行的代码,在删除数组元素并更新TableView后,将最新的items数组写入UserDefaults:
override func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCell.EditingStyle, forRowAt indexPath: IndexPath) { if editingStyle == .delete { items.remove(at: indexPath.row) tableView.deleteRows(at: [indexPath], with: .fade) // 新增:将更新后的数组同步保存到UserDefaults UserDefaults.standard.setValue(items, forKey: "items") } else if editingStyle == .insert { // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view } }
额外优化建议
- 应用启动时从UserDefaults加载数据到
items数组,确保初始数据正确:override func viewDidLoad() { super.viewDidLoad() // 加载已保存的条目 items = UserDefaults.standard.stringArray(forKey: "items") ?? [] tableView.reloadData() } - 新增条目的代码可简化,直接用内存中的
items数组更新UserDefaults,避免重复读取操作:DispatchQueue.main.async { self.items.append(text) UserDefaults.standard.setValue(self.items, forKey: "items") self.tableView.reloadData() }
内容的提问来源于stack exchange,提问作者Nour Eldeen
相关产品推荐
相关产品推荐

