Home > Software engineering >  Better way use @State or @ObservableObject
Better way use @State or @ObservableObject

Time:01-28

Hi everyone I have a question about @State vs @ObservableObject with SwiftUI

I have a view that contains a LazyHGrid To have a custom cell of the LazyHGrid I preferred to create a new struct with the custom cell.


The view hierarchy is composed as follows:

struct View1 -> struct LazyHGrid -> struct LazyHGridCustomCell

In View1 I have a text that must be replaced with content of the LazyHGridCustomCell every time it is selected.

At this point in view of my hierarchy should I use @State & @Binding to update the text or would it be better @ObservableObject?

In case I wanted to use the @State wrapper I would find myself like this:

  • struct View1 (@State)
  • struct LazyHGrid (@Binding)
  • struct LazyHGridCustomCell (@Binding)

I was wondering if this is the right way or consider @ObservableObject

I created a code example based on my question .. It was created just to let you understand what I mean to avoid being misunderstood

I was wondering if it is right to create such a situation or use an @ObservableObject

In case this path is wrong can you show me an example of the right way to go to get the correct result?

Thanks for suggestion


struct View1: View {
    @State private var name: String
    
    var body: some View {
        Text(name)
        LazyHGridView(name: $name)
    }
}

struct LazyHGridView: View { 
    @Binding var name: String
    
    var body: some View {
        LazyHGrid(rows: Array(repeating: GridItem(), count: 2)) {
            ForEach(reservationTimeItems) { item in
                LazyHGridCustomCell(name: $name)
            }
        }
    }
}
    
struct LazyHGridCustomCell: View {
    @Binding var name: String
    
    var body: some View {
        Text(name)
            .foregroundColor(.white)
    }
}

CodePudding user response:

According to Data Essentials in SwiftUI (WWDC 2020) at 9:46, you should be using State because ObservableObject is for model data.

State is designed for transient UI state that is local to a view. In this section, I want to move your attention to designing your model and explain all the tools that SwiftUI provides to you. Typically, in your app, you store and process data by using a data model that is separate from its UI. This is when you reach a critical point where you need to manage the life cycle of your data, including persisting and syncing it, handle side-effects, and, more generally, integrate it with existing components. This is when you should use ObservableObject. First, let's take a look at how ObservableObject is defined.

  •  Tags:  
  • Related