Difference Between StateObject and ObservedObject in SwiftUI

Saeid Rezaeisadrabadi
2 min readMay 6, 2024

--

In this post, I want to talk about the differences between StateObject and ObservedObject.
SwiftUI offers powerful tools for managing data and keeping your views in sync. Two of these tools, @StateObject and @ObservedObject, can seem very similar at first glance. But there's a crucial difference between them: ownership.

Generated with AI

What is StateObject?

Imagine a complex view that needs its own dedicated data manager, like a view for a shopping cart. This data manager, often called a view model, would keep track of items added, removed, and quantities.

Here’s where @StateObject comes in. By declaring a view model property with @StateObject, you're telling SwiftUI that the current view is the proud owner of this object. SwiftUI will ensure the object persists across redraws of the view, keeping your data consistent.

What are the benefits of using @StateObject?

  • Maintains state across redraws: The view model’s data won’t be reset every time the view refreshes.
  • Clear ownership: It’s explicit which view is responsible for the object’s lifecycle.

When to use @StateObject?

  • When your view needs its own dedicated view model to manage complex data.
  • When you want to ensure data consistency across view updates.

What is ObservedObject?

Now, let’s say you have another view that wants to display some of the shopping cart data, but not manage it directly. This is where @ObservedObject shines.

By using @ObservedObject, you're essentially telling SwiftUI that you want to observe an existing view model, not create a new one. This is useful for sharing data between views without creating ownership conflicts.

What are the benefits of using @ObservedObject?

  • Shared data access: Multiple views can observe and react to changes in the same view model.
  • Dependency injection: Makes view models easier to test and manage as separate units.

When to use @ObservedObject?

  • When multiple views need to access and react to the same data managed by a view model.
  • When you want to inject a view model as a dependency into a view.

Conclusion

A good rule of thumb is to use @StateObject for the initial creation of a view model within a view. Then, other views that need to access that data can use @ObservedObject to observe it.

By understanding the ownership implications of @StateObject and @ObservedObject, you can build a cleaner, more maintainable SwiftUI applications with clear data flow.

--

--

Saeid Rezaeisadrabadi
Saeid Rezaeisadrabadi

Written by Saeid Rezaeisadrabadi

Over 8 years of experience in iOS software development

No responses yet