Swift开发:如何通过FileManager永久删除数据?TableView删除重启恢复问题
解决TableView删除元素重启后复原的问题
嘿,我懂你遇到的问题啦!你现在只完成了内存层面的删除——移除了itemArray里的元素,也更新了TableView的显示,但没有把更新后的数组重新写入到你之前创建的Item.plist文件里。所以每次重启App,程序还是会从旧的plist文件里加载原来的数据,导致删除的元素又回来了。
下面是具体的解决步骤:
1. 确保你的数据模型遵循Codable协议
首先,你的itemArray里的元素类型(比如自定义的Item结构体/类)必须实现Codable协议,这样才能被编码写入plist文件:
// 举个例子,根据你的实际模型调整 struct Item: Codable { var title: String // 其他你需要的属性... }
2. 编写保存数组到plist的方法
添加一个专门的函数,用来把itemArray编码后写入到指定的文件路径:
func saveItems() { let encoder = PropertyListEncoder() do { // 把数组编码成Data let encodedData = try encoder.encode(itemArray) // 将Data写入到plist文件,覆盖旧内容 try encodedData.write(to: dataFilePath!) } catch { print("保存数据失败:\(error.localizedDescription)") } }
3. 在删除行后调用保存方法
修改你的commit editingStyle方法,在删除数组元素和TableView行之后,调用上面的saveItems()方法,把更新后的数组持久化:
override func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCell.EditingStyle, forRowAt indexPath: IndexPath) { if editingStyle == .delete { // 移除内存中的元素 itemArray.remove(at: indexPath.row) // 更新TableView显示 tableView.deleteRows(at: [indexPath], with: .automatic) // 关键一步:把更新后的数组写入文件 saveItems() } }
4. 确认加载数据的逻辑正确
另外,你需要确保在App启动时(比如viewDidLoad里)有正确的加载逻辑,从plist文件读取最新的数据到itemArray:
func loadItems() { guard let filePath = dataFilePath else { return } if let savedData = try? Data(contentsOf: filePath) { let decoder = PropertyListDecoder() do { itemArray = try decoder.decode([Item].self, from: savedData) } catch { print("加载数据失败:\(error.localizedDescription)") } } } // 在viewDidLoad里调用加载方法 override func viewDidLoad() { super.viewDidLoad() loadItems() }
这样操作后,你删除元素时不仅会更新界面和内存中的数组,还会把最新的数组状态写入到plist文件里,下次重启App就会加载删除后的最新数据啦!
内容的提问来源于stack exchange,提问作者adri567
相关产品推荐
相关产品推荐

