问题
Inside SceneDelegate
the context is passed via .environment(\.managedObjectContext, context)
why cannot it be passed via View's property? What's the advantage of doing so?
So instead of doing below
let contentView = FlightsEnrouteView()
.environment(\.managedObjectContext, context)
We can pass the context via the View's initializer
let contentView = FlightsEnrouteView(context: context)
so inside FlightsEnrouteView
should be,
struct FlightsEnrouteView: View {
var context: NSManagedObjectContext
}
Test it and it compiles
回答1:
why cannot it be passed via View's property? What's the advantage of doing so?
It can. Just it is used by other wrappers like @FetchRequest
from environment, but nobody stops you to combine them, because context is an object of reference type, so you can pass its reference anyway you want.
So the following is absolutely valid:
let contentView = FlightsEnrouteView(context: context)
.environment(\.managedObjectContext, context)
and
struct FlightsEnrouteView: View {
@EnvironmentObject(\.managedObjectContext) var envContext
var context: NSManagedObjectContext
}
来源:https://stackoverflow.com/questions/63960706/why-does-core-data-context-object-have-to-be-passed-via-environment-variable