理解如下:
- 用于存储并传递共享数据
- 用于替代environmentobject
说明:
有一个ModelData,存储了app用到的数据。
把这个数据注入到环境中
访问这个数据
问题:注入代码在哪儿写有要求吗?
先看看注入api的说明吧。
这是给view的扩展里面添加的一个方法,入参时一个范型T,要继承自AnyObject,要继承Obserable。 返回值是一个View。
此处有一个疑问,where语法,用逗号,应该表示并且吧?
确认完毕。的确是并且的意思。
接下来阅读文档说明
/// Places an observable object in the view's environment. 把一个observable对象放到这个view的环境中
/// Use this modifier to place an object that you declare with the /// doc://com.apple.documentation/documentation/Observation/Observable() /// macro into a view's environment. 使用这个修饰符来把一个对象---你通过Observable修饰符生命的对象,放到这个view的环境中
例如
For example, you can add an instance
比如添加一个自定义的observable对象Profile到ContentView的环境中
/// of a custom observable `Profile` class to the environment of a
/// `ContentView`:
///
/// @Observable class Profile { ... }
///
/// struct RootView: View {
/// @State private var currentProfile: Profile?
///
/// var body: some View {
/// ContentView()
/// .environment(currentProfile)
/// }
/// }
///
你可以在ContentView和它的后代view里面读取这个Profile对象,descendants是后代的意思。
所以这里可以知道影响范围了,把环境注入到viewa,那么viewa和其子孙view中都可以访问这个被注入到对象了
/// You then read the object inside `ContentView` or one of its descendants
/// using the ``Environment`` property wrapper:
///
/// struct ContentView: View {
/// @Environment(Profile.self) private var currentProfile: Profile
///
/// var body: some View { ... }
/// }
///
/// This modifier affects the given view, as well as that view's descendant
/// views. It has no effect outside the view hierarchy on which you call it.
/// The environment of a given view hierarchy holds only one observable
/// object of a given type.
///
/// - Note: This modifier takes an object that conforms to the
/// <doc://com.apple.documentation/documentation/Observation/Observable>
/// protocol. To add environment objects that conform to the
/// <doc://com.apple.documentation/documentation/Combine/ObservableObject>
/// protocol, use ``View/environmentObject(_:)`` instead.
///
/// - Parameter object: The object to set for this object's type in the
/// environment, or `nil` to clear an object of this type from the
/// environment.
///
/// - Returns: A view that has the specified object in its environment.
事情就很清楚了。 这个家伙就是用于給view注入可观察的对象,然后这个注入的数据,可以被注入的view以及其子孙后代的view访问到。