I know when accessing Core Data across targets I need to use an App Group and common persistentContainer configuration. I'm able to read without issue, and I can create as well.
However, where I'm stuck is when the other target creates and saves an item, the primary app's NSFetchedResultsController
doesn't see the change. If I restart the app the data then shows up, so I know it's getting stored properly. I also tried to catch the NSManagedObjectContextDidSave
notification in the primary target, but that doesn't seem to do it either.
NotificationCenter.default.addObserver(forName: Notification.Name.NSManagedObjectContextDidSave,
object: nil,
queue: nil) { notification in
print("Got called")
self.managedObjectContext.mergeChanges(fromContextDidSave: notification)
How do I let the NSFetchedResultsController in the primary target know something got saved from another target?
I'm setting up the persistentContainer like so:
lazy private var persistentContainer: NSPersistentContainer = {
let groupName = "group.com.contoso.CoolCalendar"
let url = FileManager.default
.containerURL(forSecurityApplicationGroupIdentifier: groupName)!
.appendingPathComponent("CoolCalendar.sqlite")
let container = NSPersistentContainer(name: "CoolCalendar")
container.persistentStoreDescriptions = [
NSPersistentStoreDescription(url: url)
]
container.loadPersistentStores(completionHandler: { _, error in
if let error = error as NSError? {
fatalError("Unresolved error \(error), \(error.userInfo)")
}
})
return container
}()