如何使用一个按钮删除coreData和Tableview中的数据?

时间:2019-06-05 12:29:59

标签: ios swift xcode core-data

我实际上正在做一个食谱应用程序,我已经做了持久性数据来将配料保存在列表中,但是当我想用按钮删除配料时,它第一次起作用,但是当我重新启动我的按钮时又回来了应用程式。

这是我的代码:

class AddIngredientController: UIViewController, ShowAlert {

    @IBOutlet weak var textField: UITextField!
    @IBOutlet weak var ingredientsTableView: UITableView!

    var itemArrayIngredient = [Item]()

    let context = (UIApplication.shared.delegate as! AppDelegate).persistentContainer.viewContext

    override func viewDidLoad() {
        super.viewDidLoad()
        let dataFilePath = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)
        print(dataFilePath)
        loadItems()
    }

    func saveItems() {
        do {
            try context.save()
        } catch {
            print("Error saving context \(error)")
        }
    }

    func loadItems(with request: NSFetchRequest<Item> = Item.fetchRequest()) {
        do {
            itemArrayIngredient = try context.fetch(request)
        } catch {
            print("Error fetching data from context \(error)")
        }
    }

    @IBAction func clearButton(_ sender: UIButton) {
        context.delete() //Here the problem
        itemArrayIngredient.removeAll()
        saveItems()
        ingredientsTableView.reloadData()
    }

    @IBAction func addButton(_ sender: UIButton) {
        if textField.text!.isEmpty {
            showAlert(title: "No Ingredients", message: "Please, add some ingredients to your list.")
        } else {
            newIngredientAdded()
        }
    }

    func newIngredientAdded() {
        let newItem = Item(context: context)
        newItem.title = textField.text!
        itemArrayIngredient.append(newItem)
        saveItems()
        ingredientsTableView.reloadData()
        textField.text! = ""
    }
}

extension AddIngredientController: UITableViewDataSource, UITableViewDelegate {

    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return itemArrayIngredient.count
    }

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

        let cell = tableView.dequeueReusableCell(withIdentifier: "customSearchCell", for: indexPath)
        let item = itemArrayIngredient[indexPath.row]
        cell.textLabel?.text = item.title
        cell.textLabel?.textColor = UIColor.white
        cell.textLabel?.font = UIFont(name: "Marker Felt", size: 19)
        return cell
    }

    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        saveItems()
        tableView.deselectRow(at: indexPath, animated: true)
    }
}

3 个答案:

答案 0 :(得分:0)

您需要从核心数据中删除特定对象。请参考下面的代码

let fetchRequest = NSFetchRequest(entityName: "EntityName")

if let result = try? context.fetch(fetchRequest) {
    for object in result {
        //Please check before delete operation
        if object.id == Your_Deleted_Object_ID{
            context.delete(object)
        }
    }
}

答案 1 :(得分:0)

您可以使用NSBatchDeleteRequest从特定实体中删除所有数据。请参阅以下代码。 NSBatchDeleteRequest的主要优点是,您无需枚举对象数组。

let fetch = NSFetchRequest<NSFetchRequestResult>(entityName: "EntityName")
let deleteRequest = NSBatchDeleteRequest(fetchRequest: fetch)

do {
    try context.execute(deleteRequest)
} catch {
    print(error.localizedDescription)
}

答案 2 :(得分:0)

context.delete必须带有一个参数来调用。例如

@IBAction func clearButton(_ sender: UIButton) {
    itemArrayIngredient.forEach { context.delete($0) }
    itemArrayIngredient.removeAll()
    saveItems()
    ingredientsTableView.reloadData()
}