You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何解决移除后台后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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.21 15:25:44