从tableview中删除一行

时间:2016-11-29 17:44:45

标签: xcode uitableview swift3

我正在尝试从表视图中删除一行,但是我收到此错误: ***由于未捕获的异常终止应用程序' NSInternalInconsistencyException',原因:'无效更新:第0部分中的行数无效。更新后现有部分中包含的行数(4)必须等于更新前的该部分中包含的行数(4),加上或减去从该部分插入或删除的行数(插入0,删除1),加上或减去移入的行数或超出该部分(0移入,0移出)。'

这是我的代码:

import UIKit
import CoreData

class VehiclesTableViewController: UITableViewController {

    // MARK: - Model
    var vehiclesStored = [Array<Vehicle>]() {
        didSet {
            tableView.reloadData()
        }
    }

    var managedObjectContext: NSManagedObjectContext? = (UIApplication.shared.delegate as? AppDelegate)?.managedObjectContext

    // MARK: - Lifecycle methods

    override func viewDidLoad() {
        super.viewDidLoad()
        vehiclesStored.removeAll()
        vehiclesStored.insert(Vehicle.fetchVehicles(inManagedObjectContext: managedObjectContext!)!, at: 0)

        navigationItem.title = String(vehiclesStored[0].count) + " Vehicles"
        // Uncomment the following line to preserve selection between presentations
        // self.clearsSelectionOnViewWillAppear = false

        // Uncomment the following line to display an Edit button in the navigation bar for this view controller.
        self.navigationItem.leftBarButtonItem = self.editButtonItem
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }

    // MARK: - Table view data source

    override func numberOfSections(in tableView: UITableView) -> Int {
        // #warning Incomplete implementation, return the number of sections
        return vehiclesStored.count
    }

    override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        // #warning Incomplete implementation, return the number of rows
        return vehiclesStored[section].count
    }


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

        // Configure the cell...
        let vehicles = vehiclesStored[indexPath.section][indexPath.row]
        cell.textLabel?.text = (vehicles.id_brand_model?.id_model?.brand)! + ", " + (vehicles.id_brand_model?.model)! + ", " + (vehicles.id_vehicle_type?.type)!
        let dateFormatter = DateFormatter()
        dateFormatter.dateFormat = "EEE, dd MMM yyy hh:mm:ss"
        cell.detailTextLabel?.text = String(vehicles.id as! Int64) + ", " + vehicles.licence_plate! + ", " + (vehicles.id_color?.color_description)! + ", " + dateFormatter.string(from:vehicles.date as! Date)

        return cell
    }

    // Override to support conditional editing of the table view.
    override func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool {
        // Return false if you do not want the specified item to be editable.
        return true
    }

    // Override to support editing the table view.
    override func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) {
        if editingStyle == .delete {
            // Delete the row from the data source
            vehiclesStored[0].remove(at: indexPath.row)
            tableView.deleteRows(at: [indexPath], with: .fade)
        } else if editingStyle == .insert {
            // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
        }    
    }

    /*
    // Override to support rearranging the table view.
    override func tableView(_ tableView: UITableView, moveRowAt fromIndexPath: IndexPath, to: IndexPath) {

    }
    */

    /*
    // Override to support conditional rearranging of the table view.
    override func tableView(_ tableView: UITableView, canMoveRowAt indexPath: IndexPath) -> Bool {
        // Return false if you do not want the item to be re-orderable.
        return true
    }
    */


    // MARK: - Navigation

    @IBAction func unwindVehicleList(sender: UIStoryboardSegue) {
        if let sourceViewController = sender.source as? VehicleAddViewController {
            if let vehicles = sourceViewController.vehicle {
                if let selectedIndexPath = tableView.indexPathForSelectedRow {
                    // Update an existing vehicle.
                    vehiclesStored[selectedIndexPath.section][selectedIndexPath.row] = vehicles
                    tableView.reloadRows(at: [selectedIndexPath], with: .none)
                }
                else {
                    // Add a new vehicle.
                    vehiclesStored.removeAll()
                    vehiclesStored.insert(Vehicle.fetchVehicles(inManagedObjectContext: managedObjectContext!)!, at: 0)
                    tableView.reloadData()
                }
            }
        }
    }

    // a little preparation before navigation
    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        // Get the new view controller using segue.destinationViewController.
        // Pass the selected object to the new view controller.
        if segue.identifier != nil {
            if segue.identifier == "Show Detail" {
                let vehicleDetailViewController = segue.destination as! VehicleAddViewController

                // Get the cell that generated this segue.
                if let selectedVehicleCell = sender as? UITableViewCell {
                    let indexPath = tableView.indexPath(for: selectedVehicleCell)!
                    let selectedVehicle = vehiclesStored[indexPath.section][indexPath.row]
                    vehicleDetailViewController.vehicle = selectedVehicle
                }
            }
            else if segue.identifier == "Add Item" {
                print("Adding new vehicle.")
            }
        }
    }


}

为什么会这样?

1 个答案:

答案 0 :(得分:0)

我的问题出现在我的var的didSet中,它正在重新加载数据,并且在删除行时没有检测到任何更改