UITableView didSelectRowAt在indexPath返回错误的tableViewCell

时间:2019-03-14 15:03:26

标签: swift uitableview nsfetchedresultscontroller didselectrowatindexpath

我正在制作待办计划应用程序,并且在tableViewCell中遇到了严重的错误。每当我多次选择一行时,都会在该行调用错误的indexPath。

如果我将自己的resultsController.delegate注释掉,则该应用正常运行。但是,我需要结果控制器委托用于每次制定新计划时更新表视图。

override func viewDidLoad() {
    super.viewDidLoad()

    // Create Request
    let request:NSFetchRequest<Plan> = Plan.fetchRequest()
    let sortDescriptors = NSSortDescriptor(key: "date", ascending: true) // make request more specific
    request.sortDescriptors = [sortDescriptors]

    // Init our results controller
    resultsController = NSFetchedResultsController(
        fetchRequest: request,
        managedObjectContext: coreDataStack.managedContext,
        sectionNameKeyPath: nil,
        cacheName: nil
    )
    resultsController.delegate = self

    // Perform fetch request
    do {
        try resultsController.performFetch()
    } catch {
        print("Perform fetch error \(error)")
    }
}

这是相关的 TableViewDelegates

override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
    self.performSegue(withIdentifier: "showNewPlan", sender: tableView.cellForRow(at: indexPath))
}

我还添加了我的导航准备功能。

override func prepare(for segue: UIStoryboardSegue, sender: Any?) {

    if let _ = sender as? UIBarButtonItem , let vc = segue.destination as? NewPlanViewController {
        vc.managedContext = resultsController.managedObjectContext
    }
    if let cell = sender as? UITableViewCell , let vc = segue.destination as? NewPlanViewController {
        vc.managedContext = resultsController.managedObjectContext
        if let indexPath = tableView.indexPath(for: cell) {
            let plan = resultsController.object(at: indexPath)
            vc.plan = plan
        }
    }
}

resultsControllerDelegate是我更新tableViewCells的方式。

func controller(_ controller: NSFetchedResultsController<NSFetchRequestResult>, didChange anObject: Any, at indexPath: IndexPath?, for type: NSFetchedResultsChangeType, newIndexPath: IndexPath?) {
    switch type {
    case .insert:
        if let indexPath = newIndexPath {
            tableView.insertRows(at: [indexPath], with: .automatic)
        }
    case .delete:
        if let indexPath = indexPath {
            tableView.deleteRows(at: [indexPath], with: .automatic)
        }
    case .update:
        if let indexPath = indexPath, let cell = tableView.cellForRow(at: indexPath) {
            let plan = resultsController.object(at: indexPath)
            cell.textLabel?.text = plan.title
        }
    default:
        break
    }
}

0 个答案:

没有答案