Setup:
My app uses core data & cloud kit mirroring.
For unit tests, I want to mock iCloud mirroring by setting cloudKitContainerOptions = nil of the NSPersistentStoreDescription of the persistent store used.
To mock mirroring, I want to setup a 2nd core data stack that uses the same persistent store as the normal data stack.
Additionally, the SQL persistent store is replaced by an NSInMemoryStoreType persistent store.
Problem:
I did not manage to use the same in-memory persistent store for 2 core data stacks.
Both stacks are created with a NSPersistentCloudKitContainer.
Both use the same NSPersistentStoreDescription with the same file URL, although this file URL is apparently ignored for an in-memory persistent store.
Thus, both containers use different in-memory persistent stores, and it is not possible to mock iCloud mirroring to a single persistent store.
Question:
I the intended setup possible, and if so, how?
PS: I know that I probably could use the same SQL store by specifying the same file UrL. But this had the disadvantage that the store persisted between different unit tests, and had to be reset at the beginning of each test.
It is indeed possible to set up 2 core data stacks that use the same in-memory persistent store, but they will have not all properties as an SQLite store.
Here is my test setup for the 2 core data stacks:
CoreDataCloudKitContaineris a subclass ofNSPersistentCloudKitContainer. It has a staticvar managedObjectModelthat is used duringinitof aCoreDataCloudKitContaineras well as theinitof the 2ndNSPersistentStoreCoordinator(the model must only be loaded once or core data will get confused):Note also that
addPersistentStoreuses an option[NSPersistentHistoryTrackingKey: true]that is required ifprivateStoreis defined withprivateStoreDescription.setOption(true as NSNumber, forKey: NSPersistentHistoryTrackingKey). If it is not set, one will get an errorCoreData: fault: Store opened without NSPersistentHistoryTrackingKey but previously had been opened with NSPersistentHistoryTrackingKey - Forcing into Read Only mode store at 'file://...privateStoreis initialized aswhere type is
NSSQLiteStoreTypeforprivateStoreType == .persistentStoreand.nullDevice, andNSInMemoryStoreTypeforprivateStoreType == .inMemory. Note that the option.nullDevicecreates an SQLite store in memory only, but.inMemorycreates some store in memory, but it is not a SQLite store. Infos about a.nullDevicestore can be found in this blog.A warning:
Although it is possible to set up 2 core data stacks using the same in-memory persistent store, such a store has limitations. One is that modifying the store by one stack does not trigger an
NSPersistentStoreRemoteChangeNotification, so that unit testing of iCloud mirroring is not possible. For that, one has to use a file based SQLite persistent store.