如何正确删除行?当我删除表视图中的行时,我有崩溃我有这个线程

时间:2017-11-22 17:58:01

标签: ios uitableview core-data swift4

这是主题:  '无效更新:第0节中的行数无效。更新后的现有部分中包含的行数(19)必须等于更新前该部分中包含的行数(19),再加上或减去从该部分插入或删除的行数(插入0,删除1),加上或减去移入或移出该部分的行数(0移入,0移出)。'

这是代码删除行

import UIKit
import CoreData
import Foundation

class TableViewController: UITableViewController {


    @IBOutlet weak var tableShow: UITableView!

    var person = [NSManagedObject]()


    override func viewDidLoad() {
        super.viewDidLoad()
        navigationItem.rightBarButtonItem = editButtonItem
    }

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

        let appDelegate = UIApplication.shared.delegate as! AppDelegate
        let managedContext = appDelegate.persistentContainer.viewContext
        let fetchRequest = NSFetchRequest<NSFetchRequestResult>(entityName: "Person")

        do {
            let results = try managedContext.fetch(fetchRequest)
            person = results as! [NSManagedObject]

        } catch let error as NSError {
            print("Fetching Error: \(error.userInfo)")
        }

    }

    // MARK: - Table view data source

    override func numberOfSections(in tableView: UITableView) -> Int {
        return 1
    }

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

    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath)


        let personA = person[indexPath.row]
        let firstName = personA.value(forKey: "firstName")
        let lastName = personA.value(forKey: "lastName")
        let age = personA.value(forKey: "age")
        if age != nil {

            cell.textLabel?.text = "\(firstName!) \(lastName!), age \(age!)"
        }
        else {

            cell.textLabel?.text = "\(firstName!) \(lastName!)"
        }
        return cell

    }

    override func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) {
        if editingStyle == .delete {
            var all = [[person]]

        all[indexPath.section].remove(at: indexPath.row)

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

       // tableView.reloadData()
            }

    }

    override func setEditing(_ editing: Bool, animated: Bool) {
        super.setEditing(editing, animated: animated)

        if editing {
            tableView.setEditing(true, animated: true)
        } else {
            tableView.setEditing(false, animated: true)
        }
    }

}

1 个答案:

答案 0 :(得分:0)

尝试直接从person变量中删除元素,然后重新加载数据。

override func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) {
    if editingStyle == .delete {
        person.remove(at: indexPath.row)
        tableView.reloadData()
    }
}