1
wを削除するには、次のエラーで終了している:ここでアプリケーションのtableViewから行を削除しようとした後のUITableViewの行を/ CoreDataとNSFetchedResultsController
Terminating app due to uncaught exception
'NSInternalInconsistencyException', reason: 'Invalid update: invalid
number of rows in section 0. The number of rows contained in an
existing section after the update (2) must be equal to the number of
rows contained in that section before the update (2), plus or minus
the number of rows inserted or deleted from that section (0 inserted,
1 deleted) and plus or minus the number of rows moved into or out of
that section (0 moved in, 0 moved out).'
コード:
import UIKit
import CoreData
class PlayerTableViewController: UITableViewController {
lazy var fetchedResultsController:NSFetchedResultsController<TCSpieler> = {
let fetch:NSFetchRequest<NSFetchRequestResult> = NSFetchRequest(entityName: "TCSpieler")
let sortByName = NSSortDescriptor(key: "name", ascending: true)
fetch.sortDescriptors = [sortByName]
let managedObjectContext = (UIApplication.shared.delegate as! AppDelegate).persistentContainer.viewContext
let frc = NSFetchedResultsController(fetchRequest: fetch, managedObjectContext: managedObjectContext, sectionNameKeyPath: nil, cacheName: nil)
try! frc.performFetch()
return frc as! NSFetchedResultsController<TCSpieler>
}()
// MARK: - Table view data source
override func numberOfSections(in tableView: UITableView) -> Int {
return fetchedResultsController.sections?.count ?? 1
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return fetchedResultsController.sections![section].numberOfObjects
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "PlayerCell", for: indexPath) as! PlayerTableViewCell
// Configure the cell...
cell.player = fetchedResultsController.object(at: indexPath)
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 {
let rowToDelete = fetchedResultsController.object(at: indexPath)
fetchedResultsController.managedObjectContext.delete(rowToDelete)
try! fetchedResultsController.managedObjectContext.save()
// Delete the row from the data source
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
}
}
ブレークポイントを使用して、 'fetchedResultsController'からデータを正しく削除するかどうかを確認してください。 – KrishnaCA
NSFetchedResultsControllerの代理メソッドを実装しましたか? – vadian
削除する前にセクション2にいくつの行がありますか? –