1

I have two view controllers, one is a tableView with a NSFetchedResultsController and the other is a regular viewController. My tableView is properly setup with NSFetchedResultsController delegates and is working perfect. I now have realized that just because I declare the same managed object context in each separate view that the tableView/NSFetchedresultsController will not monitor changes that I have made in the regular view controller.

This is how I declare it in each view lazy var coreDataStack = CoreDataStack(modelName: "myApp") I understand now that I need to merge my saved changes from my regular viewControllers context to my tableView/NSFetchedresultsController context so that the delegate methods can run but I am unsure how to do so. When I change create or update an object in the regular VC I add notification observers like this

 NotificationCenter.default.addObserver(self, selector: #selector(contextDidSave(_:)), name: Notification.Name.NSManagedObjectContextDidSave, object: nil)


   @objc func contextDidSave(_ notification: Notification) {
        let frc = ConversationsViewController().fetchedResultsController
        frc.managedObjectContext.mergeChanges(fromContextDidSave: notification)
        frc.managedObjectContext.processPendingChanges()
        print("Object did save: \(notification)")
    }

After I create or update an object the regular VC, notification prints successfully but no delegate methods are called in tableView/NSFetchedresultsController. I know that the objects are saving because when I restart the app they are shown in the tableView. I would greatly appreciate if anyone can point me in the right direction as to how I can notify my fetchedResultsController an object has saved. I have seen a similar question NSFetchedResultsController doesn't call controllerDidChangeContent: after update to non-fetched NSManagedObject but it is in Objective C

GBMR
  • 594
  • 1
  • 7
  • 16
  • You that that by doing ` ConversationsViewController()`, you are creating a NEW instance, not the one that you think of? – Larme Jan 14 '21 at 19:44
  • 1
    Why don't you observe `NSManagedObjectContextDidSave` in `ConversationsViewController`? – vadian Jan 14 '21 at 19:57
  • Did not know I could but I just did and it worked. @vadian – GBMR Jan 14 '21 at 20:02

0 Answers0