首页 > 解决方案 > 如何使用 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)
            }
        }

标签: iosswiftxcode

解决方案


这是添加一个新项目

@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
}

}


推荐阅读