Sitemap

Difference between @StateObject and @ObservedObject

1 min readJan 6, 2025

--

Views in SwiftUI can be redrawn frequently whenever @Published values are being observed by the view. So it is up to the developers when to use what .

@ObservedObject When a view is redrawn, the entire View is redrawn again, which means it will reset all the variables to their default ones except those which are marked in @State .

@StateObject When a view is redrawn, objects marked with @StateObject does not reinstantiated . This means the first instance of the object which we create will be persist/retained and be used whenever View is redrawn.

Get iVenky’s stories in your inbox

Join Medium for free to get updates from this writer.

Consider the below example

struct RandomNumberView: View {
@State var randomNumber = 0

var body: some View {
VStack {
Text("Random number is: \(randomNumber)")
Button("Randomize number") {
randomNumber = (0..<1000).randomElement()!
}
}.padding(.bottom)

CounterView()
}
}

struct RandomStringView: View {
@StateObject var viewModel = RandomStringViewModel()

var body: some View {
VStack {
Text("Random String is \(viewModel.updateName)")
Button("Random String") {
viewModel.randomString(length: 4)
}
}
}
}

final class RandomStringViewModel: ObservableObject {
@Published var updateName: String = ""

func randomString(length: Int) {
let letters = "abcdefghijklmnopqrstuvwxyz"
updateName = String((0..<length).map{ _ in letters.randomElement()! })
}
}

Here in the above example, if the view model is declared as below with @StateObject, the random string which was generated in the session will persist even though the view is redrawn .

@StateObject var viewModel = RandomStringViewModel()

It will reset to default when it is declared as @ObservedObject

@ObservedObject var viewModel = RandomStringViewModel()

--

--