简体   繁体   中英

Swift, CoreData: TableView not reloading data when childVC dismissed

Ok I am brand new to this and am a bit overwhelmed going through many tutorials and articles. And spent a few hours sorting through similar issues with no luck in fixing my own. I have a "AddSiteVC" to allow the user to add or delete Items that are put into CoreData and then displayed in a TableView on my "MainVC". My problem is when I press save or delete and get dismissed back to my MainVC onBtnClick the TableView doesn't update until I leave the MainVC and then come back. I don't know what I'm doing wrong but can't seem to find anything that fixes this... I don't know where my problem is so I'll include most of my MainVC code for reference. Any help would be greatly appreciated! Thanks!

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

Please make following change in the code . Because viewDidLoad will be called when viewcontroller is loaded . But as per your requirement you adding something in Modal page. So you need move the code to 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()
    }
}
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 }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM