Swift,CoreData:当childVC解散时,TableView不会重新加载数据

时间:2016-10-26 04:38:16

标签: ios uitableview core-data swift3

好的我对此我是全新的,并且通过许多教程和文章有点不知所措。花了几个小时整理类似的问题,没有运气来修复我自己的问题。我有一个" AddSiteVC"允许用户添加或删除放入CoreData的项目,然后显示在我的" MainVC"上的TableView中。我的问题是当我按下保存或删除并被解雇回到我的MainVC onBtnClick时,TableView不会更新,直到我离开MainVC然后再回来。我不知道自己做错了什么,但似乎无法找到解决问题的方法......我不知道我的问题在哪里,所以我会包含最多的问题我的MainVC代码供参考。 任何帮助将不胜感激! 谢谢!

import UIKit
import CoreData

class SitesViewController: UIViewController, UITableViewDelegate, UITableViewDataSource, NSFetchedResultsControllerDelegate {

@IBOutlet weak var tableView: UITableView!

var controller: NSFetchedResultsController<Sites>!

override func viewDidLoad() {
    super.viewDidLoad()

    tableView.delegate = self
    tableView.dataSource = self

    attemptFetch()
}

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

func configureCell(cell: SitesCell, indexPath: NSIndexPath) {
    let sites = controller.object(at: indexPath as IndexPath)
    cell.configureCell(sites: sites)
    cell.accessoryType = .detailButton
}

override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
    if segue.identifier == "AddSiteViewController" {
        if let destination = segue.destination as? AddSiteViewController {
            if let site = sender as? Sites {
                destination.siteToEdit = site
            }
        }
    }
}

func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    if let sections = controller.sections {
        let sectionInfo = sections[section]
        return sectionInfo.numberOfObjects
    }
    return 0
}

func numberOfSections(in tableView: UITableView) -> Int {
    if let sections = controller.sections {
        return sections.count
    }
    return 0
}

func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
    return 75
}

func tableView(_ tableView: UITableView, accessoryButtonTappedForRowWith indexPath: IndexPath) {
    if let objs = controller.fetchedObjects, objs.count > 0 {
        let site = objs[indexPath.row]
        performSegue(withIdentifier: "AddSiteViewController", sender: site)
    }
}

func attemptFetch() {
    let fetchRequest: NSFetchRequest<Sites> = Sites.fetchRequest()
    let alphebaticalSort = NSSortDescriptor(key: "name", ascending: true)
    fetchRequest.sortDescriptors = [alphebaticalSort]

    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)")
    }
}

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

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)
        }
        break
    case.delete:
        if let indexPath = indexPath {
            tableView.deleteRows(at: [indexPath], with: .fade)
        }
        break
    case.update:
        if let indexPath = indexPath {
            let cell = tableView.cellForRow(at: indexPath) as! SitesCell
            configureCell(cell: cell, indexPath: indexPath as NSIndexPath)
        }
        break
    case.move:
        if let indexPath = indexPath {
            tableView.deleteRows(at: [indexPath], with: .fade)
        }
        if let indexPath = newIndexPath {
            tableView.insertRows(at: [indexPath], with: .fade)
        }
        break
    }
}

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

2 个答案:

答案 0 :(得分:0)

请在代码中进行以下更改。因为加载viewcontroller时将调用viewDidLoad。但根据您的要求,您可以在Modal页面中添加内容。因此,您需要将代码移至viewWillAppear

import UIKit
import CoreData

class SitesViewController: UIViewController, UITableViewDelegate, UITableViewDataSource, NSFetchedResultsControllerDelegate {

@IBOutlet weak var tableView: UITableView!

var controller: NSFetchedResultsController<Sites>!

    override func viewDidLoad() {
        super.viewDidLoad()

        tableView.delegate = self
        tableView.dataSource = self


    }

    override func viewWillAppear(animated: Bool) {
        super.viewWillAppear(animated)
        attemptFetch()
    }
}

答案 1 :(得分:-1)

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