如何从UITableView swift 4中删除一行,其中使用CoreData存储数据?

时间:2019-02-23 19:21:32

标签: ios swift uitableview core-data

我是一个初学者,试图学习iOS和Swift的基本概念。因此,我正在制作一个演示应用程序,其中使用UITableView存储人员姓名。为了使应用程序存储持久化,我仅使用了核心数据和一个名为“ Person”的实体,并将其单个属性称为“ name”,即字符串值。要升级此应用程序,我需要添加删除功能。正如我们在许多iOS应用中所看到的,向左滑动时具有删除功能,我想在此应用中实现相同的功能。我已经研究过各种解决方案,但是我无法真正掌握如何在同一时间删除一行并更新核心数据中的表。数小时以来,我一直试图解决此问题,试图使用滑动手势删除UITableView中的一行。任何帮助将不胜感激。

下面是我的代码:

ViewController.swift

import UIKit
import CoreData

class ViewController: UIViewController {

    @IBOutlet weak var tableView: UITableView!

    var people: [NSManagedObject] = []

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.
        title = "The List"
        tableView.register(UITableViewCell.self,
                           forCellReuseIdentifier: "Cell")
    }

    // Implement the addName IBAction
    @IBAction func addName(_ sender: UIBarButtonItem) {
        let alert = UIAlertController(title: "New Name", message: "Add a new name", preferredStyle: .alert)
        let saveAction = UIAlertAction (title: "Save", style: .default) {
            [unowned self] action in
            guard let textField = alert.textFields?.first, let nameToSave = textField.text else {
                return
            }
            self.save(name: nameToSave)
            self.tableView.reloadData()
        }
        let cancelAction = UIAlertAction(title: "Cancel", style: .cancel)
        alert.addTextField()

        alert.addAction(saveAction)
        alert.addAction(cancelAction)

        present(alert, animated: true)
    }

    // MARK: - SAVING TO CORE DATA

    // CoreData kicks in here!
    func save(name: String) {
        guard let appDelegate = UIApplication.shared.delegate as? AppDelegate else {
            return
        }
        // 1
        let managedContext = appDelegate.persistentContainer.viewContext

        // 2
        let entity = NSEntityDescription.entity(forEntityName: "Person", in: managedContext)!
        let person = NSManagedObject(entity: entity, insertInto: managedContext)

        // 3
        person.setValue(name, forKeyPath: "name")

        // 4
        do {
            try managedContext.save()
            people.append(person)
        } catch let error as NSError {
            print("Could not save. \(error), \(error.userInfo)")
        }
    }

    // MARK: - FETCHING FROM CORE DATA

    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)

        // 1
        guard let appDelegate = UIApplication.shared.delegate as? AppDelegate else {
            return
        }

        let managedContext = appDelegate.persistentContainer.viewContext

        // 2
        let fetchRequest = NSFetchRequest<NSManagedObject>(entityName: "Person")

        // 3
        do {
            people = try
                managedContext.fetch(fetchRequest)
        } catch let error as NSError {
            print("Could not save. \(error), \(error.userInfo)")
        }
    }
}
// MARK: - UITableViewDataSource

extension ViewController: UITableViewDataSource {

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

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let person = people[indexPath.row]
        let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath)
        cell.textLabel?.text = person.value(forKeyPath: "name") as? String
        return cell
    }
}

// MARK: - UITableViewDelegate

extension ViewController: UITableViewDelegate {
    func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool {
        return true
    }

    func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCell.EditingStyle, forRowAt indexPath: IndexPath) {
        if (editingStyle == .delete) {
            // handle delete (by removing the data from your array and updating the tableview)

        }
    }
}

应用程序屏幕:

enter image description here

数据模型:

enter image description here

1 个答案:

答案 0 :(得分:1)

您必须通过在托管对象上下文上调用delete(_ :)来删除托管对象,例如:

guard let appDelegate = UIApplication.shared.delegate as? AppDelegate else {
    return
}
let managedContext = appDelegate.persistentContainer.viewContext
let person = people[indexPath.row]
managedContext.delete(person)

要提交更改,请在托管对象上下文上调用save():

try? managedContext.save()

然后,别忘了还要更新视图控制器中的人员缓存:

people.remove(at: indexPath.row)

最后,删除表格视图中的行:

tableView.deleteRows(at: [indexPath], with: .automatic)

这应该完成您想要的。

因此缺少的实现可能是:

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

        // delete the person in core data
        guard let appDelegate = UIApplication.shared.delegate as? AppDelegate else {
            return
        }
        let managedContext = appDelegate.persistentContainer.viewContext
        let person = people[indexPath.row]
        managedContext.delete(person)
        try? managedContext.save()

        // remove the person from cache
        people.remove(at: indexPath.row)

        // delete row from table view
        tableView.deleteRows(at: [indexPath], with: .automatic)
    }
}