ios - 如何使用 FileManager 永久删除 swift 中的条目
问题描述
我是 swift 编程的新手。我编写了一个应用程序,您可以在其中向表格视图添加一些元素。我通过 FileManager 在我的模拟器 iPhone 上保存了数据。现在我想从我的表格视图中永久删除一个元素。
我使用了一种名为 commit editingStyle 的方法来删除表格视图中的一行。这是有效的,但如果我重新启动我的应用程序,该元素仍然存在。
//create the file
let dataFilePath = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first?.appendingPathComponent("Item.plist")
//delete the file
override func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCell.EditingStyle, forRowAt indexPath: IndexPath) {
if editingStyle == UITableViewCell.EditingStyle.delete {
itemArray.remove(at: indexPath.row)
tableView.deleteRows(at: [indexPath], with: UITableView.RowAnimation.automatic)
}
}
解决方案
这是添加一个新项目
@IBAction func addNewToDoItem(_ sender: UIBarButtonItem) {
var textField = UITextField()
let alert = UIAlertController(title: "Neues Todo", message: "", preferredStyle: .alert)
let action = UIAlertAction(title: "ToDo hinzufügen", style: .default) { (action) in
// Item was der Nutzer ertsellen wird
let itemObject = Item(title: textField.text!) // hinzufügen, das was der Nutzer ins Textfield eingibt
self.itemArray.append(itemObject)
// Daten dauerhaft speichern
self.saveItems()
self.tableView.reloadData()
}
let cancelAction = UIAlertAction(title: "Abbrechen", style: .default) { (cancelAction) in
// Abbrechen
}
alert.addTextField { (alertTextField) in
alertTextField.placeholder = "Todo eintragen"
textField = alertTextField
}
alert.addAction(action)
alert.addAction(cancelAction)
present(alert, animated: true, completion: nil)
}
安全数据:
func saveItems() {
let encoder = PropertyListEncoder()
do {
let data = try encoder.encode(itemArray)
try data.write(to: dataFilePath!)
} catch {
print("Fehler beim schreiben der Dateien", error)
}
}
这是我的 itemArray 和他自己的课程:
var itemArray = [Item]()
class Item: Codable { // Aus Encodable und Decodable wird Codable
var title : String = ""
var done : Bool = false
init(title : String) {
self.title = title
}
init(title: String, done: Bool) {
self.title = title
self.done = done
}
}
推荐阅读
- pandas - 将时间序列数据帧转换为单变量 LSTM 分类器的输入
- python - 为什么过滤器在 Django 模板的迭代中不会改变值
- javascript - 使用Javascript删除地图中的多个键集?
- javascript - 身份验证令牌获取确实存在API问题
- node.js - Nodejs发布视图计数保存数据库
- elasticsearch - elasticsearch:无法解析[文本]类型的字段
- visual-studio - 无法使用“source”命令在 VSCode 上为我的烧瓶应用程序激活环境
- sql - 获取每种产品的最新两条线并获取价格和日期
- swift - Swift UrlSession SSL CLIENT CERTIFICATE 在 1-2 天后停止工作
- reactjs - 如何从使用状态或其他钩子 React JS 中仅获取一个设置状态函数,