简体   繁体   中英

Refresh Core Data in ViewController when Modal View (2nd view) is Dismissed - Swift

I'm trying to figure out how to reload my UIViewController after I dismiss a Modal View. What's happening is I segue from View 1 (my UIVIewController) to a Modal View where I make an update to Core Data. Upon completion, I save the Core Data and dismiss the Modal View, sending the user back to View 1 (the UIViewController). Problem is the UIViewController is not pulling the updated change to the Core Data (but instead is presenting the old information, because it has not been refreshed).

This was the closest answer I think that could work, but I'm having trouble translating from Objective-C to Swift.

Any ideas? Thanks in advance for the help.

Here is quick NSFetchedResultsController example

override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.

            do {
                try fetchedResultsController.performFetch()
            } catch {
                print("An error occurred")
            }
    }

private lazy var fetchedResultsController: NSFetchedResultsController = {
        let animalsFetchRequest = NSFetchRequest(entityName: "Animal")
        let sortDescriptor = NSSortDescriptor(key: "classification.order", ascending: true)
        animalsFetchRequest.sortDescriptors = [sortDescriptor]

        let frc = NSFetchedResultsController(
            fetchRequest: animalsFetchRequest,
            managedObjectContext: self.context,
            sectionNameKeyPath: nil,
            cacheName: nil)

        frc.delegate = self

        return frc
}()

// delegate method

func controllerDidChangeContent(controller: NSFetchedResultsController) {
            // update UI
}

My suggestion for this issue is to create delegate that will notify View 1.

For instance:

in presented view controller create delegate:

protocol NotifyReloadCoreData
    func notifyDelegate()
end

create property of view controller:

var delegate: NotifyReloadCoreData?

when press save or something like that :

delegate.notifyDelegate()

in your View 1

class UIViewController1: UIViewController, NotifyReloadCoreData

and implement function

func notifyDelegate(){
    // reload core data here
}

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