问题
TL;DR: I have two 'Persistent Store Coordinators' who open the same 'Store file'. When one Coordinator writes changes, the other is unaware of it.
In my document-based app, I need to have multiple databases:
1. Document database (one per document)
2. Shared database (visible by all documents)
Here's how I set up my stack:
Having that setup is great because:
- Documents can't access each others stores
- Every document has access to the shared database file.
But here's a problem. Suppose I have two windows opened:
- Document window
- App window that is not backed by a document. It just displays what's in the "shared database" using
NSFetchedResultsController
.
Now, when the document is editing a "shared database", the changes are not immediately updated in the other window. My guess is that because those windows don't share a persistent store coordinator, they don't know when the underlying file has changed.
A solution would be to use a single 'Persistent Store Coordinator'. However, this would lead to documents having access to each others stores which is very dangerous.
Is there any solution to this problem?
Edit
I come up with the solution to simply observe 'did save' notifications performed by a document's context and merge changes. Would that be the right approach?
NotificationCenter.default.addObserver(forName: .NSManagedObjectContextDidSave,
object: nil,
queue: .main) { (notification) in
guard let context = notification.object as? NSManagedObjectContext else { return }
guard context.persistentStoreCoordinator != nil else { return }
sharedAppContainer.viewContext.mergeChanges(fromContextDidSave: notification)
}
来源:https://stackoverflow.com/questions/64808268/multiple-persistent-store-coordinators-opening-the-same-store-dont-see-each