我有一个mainVC,我在其中执行提取请求。
然后,我将获取的数据传递给第二个视图控制器(HomeVc),然后传递给第三个视图控制器(MyparamsVc)
在第三个VC中,我有一个tableView,其中列出了所有与我在主VC中获取的实体具有一对一关系的参数

在第四个View控制器中,我通过表单(addParamVC)添加新参数。保存后,我关闭控制器并弹出上一个(MyparamsVc)。
我的问题是,除非我回到HomeVC,然后再次进入MyparamsVC,否则tableview不会使用新数据进行更新。

我已经实现了func controllerDidChange一个对象,但是由于我没有在同一控制器中执行提取操作,因此永远不会调用该函数...我如何用新数据更新tableview?

MainVc fetchRequest:

 var controller: NSFetchedResultsController<SwimminPool>!

override func viewDidLoad() {
    super.viewDidLoad()

    tableView.delegate = self
    tableView.dataSource = self

    attemptFetch()

}
func attemptFetch() {

    let fetchRequest: NSFetchRequest<SwimminPool> = SwimminPool.fetchRequest()
    let dataSort = NSSortDescriptor(key: "poolCreatedAt", ascending: false)
    fetchRequest.sortDescriptors = [dataSort]


     let controller = NSFetchedResultsController(fetchRequest: fetchRequest, managedObjectContext: context, sectionNameKeyPath: nil, cacheName: nil)

    controller.delegate = self
    self.controller = controller

    do {
        try controller.performFetch()
    } catch {
        let error = error as NSError
        print("\(error.debugDescription)")
    }

}


addParamVC保存功能:

var swimmingPoolToConnect: SwimmingPool!
var parameterToEdit: Parameter?

@IBAction func saveBtnPressed(_ sender: Any) {

    var parameter: Parameter

    if parameterToEdit == nil {
        parameter = Parameter(context:context)
    } else {
        parameter = parameterToEdit!
    }

    if let pH = phTextField.text?.characters.split(separator: ",").joined(separator: ".") {
        if let pHnoComma =  Double(String(pH)) {
        parameter.paramPH = pHnoComma
        }
    }
  parameter.createdAt = Date()

    swimmingPoolToConnect.addToParameters(parameter)

    ad.saveContext()
    self.presentingViewController?.dismiss(animated: true, completion: nil)
}


MyparamsVC:

 var parameters = [Parameter]()
var swimmingPool: SwimmingPool! {
    didSet {
        parameters = (swimmingPool.parameters?.allObjects as! [Parameter]).sorted(by: {$0.createdAt! > $1.createdAt!})
    }
}

var controller: NSFetchedResultsController<Parameter>?

 func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: "ParamCell", for: indexPath) as! ParamCell
    configureCell(cell: cell, indexPath: indexPath)
    return cell
}

 func configureCell(cell: ParamCell, indexPath: IndexPath) {

    let param = parameters[indexPath.row]
    cell.configureCell(parameter: param)
}

func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {

  let  parameterToPass = parameters[indexPath.row]
        DispatchQueue.main.async { () -> Void in
            self.performSegue(withIdentifier: "MyParameterDetail", sender: parameterToPass)
        }
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
      return parameters.count
   }
func numberOfSections(in tableView: UITableView) -> Int {
    return 1
}

  //Never enter these func

func controllerWillChangeContent(_ controller: NSFetchedResultsController<NSFetchRequestResult>) {
    tableView.beginUpdates()
}

func controllerDidChangeContent(_ controller: NSFetchedResultsController<NSFetchRequestResult>) {
    tableView.endUpdates()
}

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: .fade)

        }

    case.delete:
        if let indexPath = indexPath{
            tableView.deleteRows(at: [indexPath], with: .fade)
        }

    case.update:
        if let indexPath = indexPath{
            let cell = tableView.cellForRow(at: indexPath) as! ParamCell
            configureCell(cell: cell, indexPath: indexPath)
        }

    case.move:
        if let indexPath = indexPath{
            tableView.deleteRows(at: [indexPath], with: .fade)
        }
        if let indexPath = newIndexPath{
            tableView.insertRows(at: [indexPath], with: .fade)
        }
    }
}

最佳答案

由于您具有对当前视图控制器的引用,因此将项目添加到parameters数组中,并在MyparamsVC中从addParamVC插入一行

ad.saveContext()
let paramsVC = self.presentingViewController as! MyparamsVC
let lastRow = paramsVC.parameters.count
paramsVC.parameters.append(parameter)
paramsVC.tableView.insertRows(at: [NSIndexPath(row: lastRow, section: 0)], with: .none)
paramsVC.dismiss(animated: true, completion: nil)


甚至在dismiss方法的完成处理程序中

ad.saveContext()
let paramsVC = self.presentingViewController as! MyparamsVC

paramsVC.dismiss(animated: true) {
    let lastRow = paramsVC.parameters.count
    paramsVC.parameters.append(parameter)
    paramsVC.tableView.insertRows(at: [NSIndexPath(row: lastRow, section: 0)], with: .none)
}

09-27 03:27