I further investigated this issue. The problem seems to be in the following line. Here I inject the viewContext into my view hierarchy.
ContentView()
.environment(\.managedObjectContext, persistence.container.viewContext)
First I deactivate the CloudKit Sync. The persistence container will be reinitialized. Therefore, I get a new instance of the viewContext.
021-12-04 22:08:19.063535+0100 TestApp[67682:1918331] [persistence] Deactivating Core Data CloudKit sync.
2021-12-04 22:08:19.063750+0100 TestApp[67682:1918331] [persistence] Persistence -> viewContext before deactivating cloudKit = <NSManagedObjectContext: 0x60000129d040>
2021-12-04 22:08:19.071889+0100 TestApp[67682:1918331] [persistence] Persistence set to local CoreData.
2021-12-04 22:08:19.102950+0100 TestApp[67682:1918331] [persistence] Persistence -> viewContext after deactivating cloudKit = <NSManagedObjectContext: 0x6000012f4ea0>
Afterwards I add a new test entity to the viewContext. The viewContext stored in the appDelegate has been set correctly. The @Environment(\.managedObjectContext) private var viewContext ones it not updated automatically.
Is there a way to force the update?
2021-12-04 22:08:47.352342+0100 TestApp[67682:1918331] [common] Adding test entitiy.
2021-12-04 22:08:47.352552+0100 TestApp[67682:1918331] [common] ShotResultList -> environment viewContext = <NSManagedObjectContext: 0x60000129d040>
2021-12-04 22:08:47.352699+0100 TestApp[67682:1918331] [common] ShotResultList -> appDelegate viewContext = <NSManagedObjectContext: 0x6000012f4ea0>
Topic:
UI Frameworks
SubTopic:
SwiftUI
Tags: