从 tableview 中删除一行

Posted

技术标签:

【中文标题】从 tableview 中删除一行【英文标题】:deleting a row from a tableview 【发布时间】:2016-11-29 17:44:44 【问题描述】:

我正在尝试从表视图中删除一行,但出现此错误: *** 由于未捕获的异常“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.")
            
        
    



这是为什么呢?

【问题讨论】:

您是否在 numberOfRows 中返回vehiclesStored[section] 部分? 是的,在覆盖 func tableView 中返回车辆存储[section].count 拜托,您能在设置表格视图的位置显示整个代码吗? 添加了整个代码 【参考方案1】:

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

【讨论】:

以上是关于从 tableview 中删除一行的主要内容,如果未能解决你的问题,请参考以下文章

从 tableView 中删除一行,在 section 中有多行

以编程方式从带有动画的 customCell 类中的 tableView 中删除一行

从 tableview 部分删除最后一行时,iOS 应用程序崩溃

在 tableview 的文本字段中搜索

从 TableView 中的 CoreData 中删除实体时出错

在ios7中删除TableView的最后一行时出现动画问题