In a SwiftUI view, by default FetchRequest fetches from the managedObjectContext environment value. If instead the view wants to fetch into an isolated context, for example to make discardable edits without polluting the context of other views, how can it change the context that FetchRequest uses?
One option is to wrap the view in an outer view that creates the isolated context and then calls the wrapped view using it:
var body: some View {
WrappedView().environment(\.managedObjectContext, isolatedContext)
}
This is tedious, however. You have to create two views and pass all the wrapped views' arguments through the wrapper. Is there a better way to tell FetchRequest which context to use?
If you use the standard
PersistentControllerthat Apple gives as a startup you could try usingYour
Viewwould need this property to make it work.@Stateshouldn't be necessary since the changes are being done in the background by other means such as notifications.Then to test it out using most of the sample code from Apple.
Also, something to note is that you have to set
In order for the main context to show the changes done after saving the
privateContext. I put it in thePersistenceControllerinitright after theloadPersistentStoresclosure.