-1

I have a SwiftUI app using Core Data and CloudKit with the NSPersistentCloudKitContainer. I pass the NSManagedObjectContext to my views with an environment variable like so:

WindowGroup {
    HomePage()
        .environment(\.managedObjectContext, DataManager.instance.context)
}

I have a toggle for tuning iCloud sync on and off, which generates the new NSPersistentCloudKitContainer, which in turn creates a new context. However, all the fetched data before with the @FetchRequest still uses the previous context from the environment object, hence manipulating it is no longer possible and I get errors.

I need to pass the new context to my views, so that @FetchRequest would use it instead. How can I do that?

Grant Oganyan
  • 352
  • 1
  • 11

1 Answers1

0

NSPersistentCloudKitContainer is just a wrapper for a core data stack where the first store description is configured for CloudKit. It isn't a good idea to completely replace it, instead you can just add or remove stores and reset the context. You can also have a cloud store and a local store active at the same time and use assign to choose which store to save an object to. Same thing for fetching. This can be achieved with configurations and was demoed in one of the WWDC talks.

If @FetchRequest really doesn't update when the context environment value changes then that's a bug and we'll have to submit a feedback request to get it fixed.

malhal
  • 26,330
  • 7
  • 115
  • 133