首页 > 解决方案 > 从 CoreData 中删除字符串

问题描述

我在从我的核心数据中删除一个项目时遇到问题,并且查看了许多其他示例和问题 - 他们都说要删除 anNSManagedObject而我试图删除位于indexPath.row( 这是 a String) 的项目。

var itemsArray = [String]()
let context = (UIApplication.shared.delegate as! AppDelegate).persistentContainer.viewContext

我会在以下函数中添加什么?

func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCell.EditingStyle, forRowAt indexPath: IndexPath) {
    if (editingStyle == .delete) {

    }
}

在 Core Data 中加载项目

func loadItems() {
    let request = NSFetchRequest<NSFetchRequestResult>(entityName: "Items")
    request.returnsObjectsAsFaults = false

    do {
        let results = try context.fetch(request)
        if results.count > 0 {
            for result in results as! [NSManagedObject] {
                if let product = result.value(forKey: "product") as? String {
                    self.itemsArray.append(product)
                }
            }
        }
    } catch {
        print("Error")
    }
}

标签: swiftuitableviewcore-data

解决方案


为了能够删除您必须使用NSManagedObject作为数据源的对象

var itemsArray = [Items]()

可以loadItems减少到

func loadItems() throws {
    let request = NSFetchRequest<Items>(entityName: "Items")
    request.returnsObjectsAsFaults = false
    itemsArray = try context.fetch(request)

}

do - catch块放在loadItems()调用周围并打印error实例,而不是无意义的文字字符串。

cellForRow使用中

let item = itemArray[indexPath.row]
let product = item.product

要删除项目,您必须将其从数据源中删除,然后删除上下文中的项目,然后保存上下文:

func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCell.EditingStyle, forRowAt indexPath: IndexPath) {
    if editingStyle == .delete {
       let objectToDelete = itemArray[indexPath.row]
       itemArray.remove(at: indexPath.row)
       context.delete(objectToDelete)
       // here add code to save the context
       self.tableView.deleteRows(at: [indexPath], with: .fade) // and you have to update the table view
    }
}

推荐阅读