swiftUI中的观察者系统

swiftUI中的观察者系统有两套:
1、基于swift宏的Observation
2、旧的ObservableObject
官方迁移说明

新的Observation优点:

  • Tracking optionals and collections of objects, which isn’t possible when using Observable Object.

  • Using existing data flow primitives like State and Environment instead of object-based equivalents such as State Object and Environment Object.

  • Updating views based on changes to the observable properties that a view’s body reads instead of any property changes that occur to an observable object, which can help improve your app’s performance.

两套导致各种ObservableObjectObservedObjectObservation各种关键字,看的人只犯迷糊,大概记录一下各个关键字的用法和含义。

ObservableObject中:class类型的model要实现ObservableObject协议,同时需要在被监听的属性前需要添加@Published,作为环境变量被导入时需要用@StateObject修饰,读取环境变量时需要使用@EnvironmentObject修饰,在view中绑定使用时,需要使用@ObservedObject修饰model。

Observation中:只需要@Observation修饰class即可,不需要额外标注属性需要添加监听,作为环境变量被导入时需要使用@State修饰,读取环境变量时需要使用@Environment(Type.self)修饰,在view中绑定使用时,需要使用@Bindable修饰model。。

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。