In SwiftUI, both @ObservedObject and @StateObject contain property wrappers that are used in conformance to the ObservableObject protocol at views. However, they serve different purposes and have different use cases:
class MyModel: ObservableObject {
@Published var data: String = ""
}
struct ParentView: View {
@StateObject private var model = MyModel() // Owns MyModel instance
var body: some View {
ChildView(model: model) // Passes existing instance to ChildView
}
}
struct ChildView: View {
@ObservedObject var model: MyModel // Observes existing MyModel instance
var body: some View {
Text(model.data)
}
}
class MyModel: ObservableObject {
@Published var data: String = ""
}
struct MyView: View {
@StateObject private var model = MyModel() // Creates and owns MyModel instance
var body: some View {
Text(model.data)
}
}
The performance with an @ObservedObject does matter when the View is recreated frequently with a heavy weight object, but not an issue when the @ObservedObject is not complex.
Apply @StateObject when editing the instance of the observable object within a view from the other view. On the contrary, there is @ObservedObject: it is used when it is observed that an instance of an observable object is retrieved from a parent view or other source. This distinction is effective when or with respect to the lifecycle and ownership of observable objects in SwiftUI applications.
Ready to transform your business with our technology solutions? Contact Us today to Leverage Our iOS Expertise.
0