Why does Core Data context object have to be passed via environment variable?

穿精又带淫゛_ 提交于 2021-02-10 18:10:36

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!