Multiple 'Persistent Store Coordinators' opening the same 'Store' don't see each others changes

大城市里の小女人 提交于 2021-01-29 06:51:59

问题


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:

  1. Documents can't access each others stores
  2. Every document has access to the shared database file.

But here's a problem. Suppose I have two windows opened:

  1. Document window
  2. 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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!