NSPersistentCloudKitContainer written to by multiple processes

Viewed 172

I have an app using iCloud and Core Data through NSPersistentCloudKitContainer. The container and related code are in a shared framework and most things are running fine. In addition to the app itself, I have a share extension and an intents extension.

The thing I'm having trouble with is if one of the extensions writes to the database while the app is active. NSPersistentCloudKitContainer seems to do some magic in both processes, and when it finds the magic already done, it fails to update certain data. For example, I have one-to-one relationships between two managed objects (which need to have inverses with cloudkit backed models). One side of the relationship becomes valid while the other one is nil.

I get errors in the console saying that CloudKit+CoreData could not merge differences between the database and the cache of the container. I'm pretty sure this is a oversight in NSPersistentCloudKitContainer where this particular scenario (shared framework, multiple open processes) wasn't taken into consideration.

Has anyone had any luck using NSPersistentCloudKitContainer and saving data with relationships from extensions?

1 Answers

Assuming your SQLite store file is in an App Group container...have you tried only using NSPersistentCloudKitContainer in the app and the regular NSPersistentContainer in the extension? You could pass a param into your shared framework class init. And you'll probably need to turn on persistent tracking and remote notifications the same way the cloud container does, so that when the app launches the CoreData framework can find the changes in the history and then export them to CloudKit for mirroring.

The underlying question here is if there are 2 whole apps (not app+extension) can both can use the NSPersistentCloudKitContainer with a store in an App Group container simultaneously? E.g. on macOS or split screen on iPadOS. Has it been designed to only sync from one app at a time? I'll see if I can figure it out and update my answer.

Edit: I asked this in this year's WWDC lounge (2022) and they said this isn't supported.

Related