首页 文章

从UITableView中删除行时出错

提问于
浏览
0

我在尝试从UITableView中删除时遇到错误 . 我的TableView来自CoreData . 这是我的代码 .

func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) {
    if (editingStyle == UITableViewCellEditingStyle.delete) {
        let appDelegate = UIApplication.shared.delegate as! AppDelegate
        let context = appDelegate.persistentContainer.viewContext

        context.delete(mealCore[indexPath.row])
        appDelegate.saveContext()
        print("context saved")
        tableView.deleteRows(at: [indexPath], with: .fade)
    }
}

我的上下文得到了保存 . 但是当它试图从tableview中删除它时,它会崩溃并出现以下错误:

无效更新:第0节中的行数无效 . 更新后的现有部分中包含的行数(5)必须等于更新前该部分中包含的行数(5),加上或减去从该部分插入或删除的行数(0插入,1删除)和加或减移入或移出该部分的行数(0移入,0移出) .

非常感谢任何建议 . 谢谢!!!

只是添加一些可能有用的代码?我可能做错了什么:var mealCore = NSManagedObject public func tableView(_ tableView:UITableView,cellForRowAt indexPath:IndexPath) - > UITableViewCell {

let cell = tableView.dequeueReusableCell(withIdentifier: "Cell") as! CustomTableViewCell
    let dateFormatter = DateFormatter()
    dateFormatter.dateFormat="dd/mm/yyyy"


    let mealRec = mealCore[indexPath.row]

    cell.mealName!.text = mealRec.value(forKey: "meal") as? String

    if let dateHolder = mealRec.value(forKey: "mealdate"){

       cell.mealDate.text = dateFormatter.string(from: dateHolder as! Date)
    }
    if let data = mealRec.value(forKey: "mealimage")as? NSData {
        cell.mealImage?.image = UIImage(data: data as Data)
    }

    return cell

}

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

    let managedContext = appDelegate.persistentContainer.viewContext

    let fetchRequest = NSFetchRequest<NSFetchRequestResult>(entityName:"FoodLog")

    do {
        let results = try managedContext.fetch(fetchRequest)
        mealCore = results as! [NSManagedObject]
    } catch let error as NSError {
        print("Could not fetch \(error), \(error.userInfo)")
    }
}

public func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {

    return mealCore.count
}

2 回答

  • 3

    您需要从 mealCore 数组中删除对象 .

    mealCore.remove(atIndex: indexPath.row)
    
  • -1

    尝试拨打 beginUpdatesendUpdates ,如下所示:

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

相关问题