Search code examples
iosswiftcore-datansfetchedresultscontroller

NSFetchedResultsController not seeing inserts made by extension


I have an iOS app structured like this

  • Main Application (the main iOS app)
  • Intents Extension (Siri integration)
  • Shared Framework (shared library for interacting with Core Data. This allows both the main application and the intents extension to use the same Core Data store)

My issue is that when I insert something into Core Data using the Intents Extension, it doesn't appear in the Main Application's UITableView until I manually refresh the fetchedResultsController like this:

NSFetchedResultsController<NSFetchRequestResult>.deleteCache(withName: "myCache")
try? fetchedResultsController.performFetch()
tableView.reloadData()

Is there a way to make the fetchedResultsController see the changes without having to manually refresh everything?


Note: If I insert something into core data from the Main Application, the fetchedResultsController automatically sees the change and updates the table (like expected)


Solution

  • To share a database between an app and extension you need to implement Persistent History Tracking. For an introduction see WWDC 2017 What's New in Core Data at 20:49 and for sample code see the documentation Consuming Relevant Store Changes.

    The basic idea is to enable the store option NSPersistentHistoryTrackingKey, observe NSPersistentStoreRemoteChangeNotification, upon being notified you should fetch the changes using NSPersistentHistoryChangeRequest and then merge into the context using mergeChangesFromContextDidSaveNotification and transaction.objectIDNotification. Your NSFetchedResultsController will then update accordingly.