为什么必须通过环境变量传递Core Data上下文对象? [英] Why does Core Data context object have to be passed via environment variable?

查看:54
本文介绍了为什么必须通过环境变量传递Core Data上下文对象?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

SceneDelegate 内部,上下文是通过 .environment(\.managedObjectContext,context)传递的,为什么不能通过View的属性传递它呢?这样做有什么好处?

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?

所以不要在下面做

let contentView = FlightsEnrouteView()
    .environment(\.managedObjectContext, context)

我们可以通过View的初始化程序传递上下文

We can pass the context via the View's initializer

let contentView = FlightsEnrouteView(context: context)

因此在 FlightsEnrouteView 内部应该是

struct FlightsEnrouteView: View {
    var context: NSManagedObjectContext
}

测试并编译

推荐答案

为什么不能通过View的属性传递它?这样做有什么好处?

why cannot it be passed via View's property? What's the advantage of doing so?

可以.只是它被环境中的其他包装器(如 @FetchRequest )使用,但是没有人阻止您将它们组合在一起,因为上下文是引用类型的对象,因此您可以随时传递其引用.

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)

struct FlightsEnrouteView: View {
    @EnvironmentObject(\.managedObjectContext) var envContext
    var context: NSManagedObjectContext
}

这篇关于为什么必须通过环境变量传递Core Data上下文对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆