NEW: Start my new Ultimate Portfolio App course with a free Hacking with Swift+ trial! >>

How to use @StateObject to create and monitor external objects

Paul Hudson    @twostraws   

Updated for Xcode 12.5

SwiftUI’s @StateObject property wrapper is a specialized form of @ObservedObject, having all the same functionality with one important addition: it should be used to create observed objects, rather than just store one that was passed in externally.

When you add a property to a view using @StateObject, SwiftUI considers that view to be the owner of the observable object. All other views where you pass that object should use @ObservedObject.

This really matters. Seriously, if you get this wrong you might your object gets destroyed by accident, which will cause your app to crash seemingly randomly.

So, to be clear: you should create your observable object somewhere using @StateObject, and in all subsequent places where you pass that object you should use @ObservedObject.

Here’s an example in code:

// An example class to work with
class User: ObservableObject {
    @Published var name = "Taylor"
    @Published var age = 26

// A view that creates and owns the User object.
struct ContentView: View {
    @StateObject var user = User()

    var body: some View {
        NavigationView {
            NavigationLink(destination: DetailView(user: user)) {
                Text("Show detail view")

// A view that monitors the User object for changes, but
// doesn't own it.
struct DetailView: View {
    @ObservedObject var user: User

    var body: some View {
        Text("Hello, \(!")

If you’re finding it hard to remember the distinction, try this: whenever you see “State” in a property wrapper, e.g. @State, @StateObject,@GestureState`, it means “the current view owns this data.”

Hacking with Swift is sponsored by Emerge

SPONSORED Emerge helps iOS devs write better, smaller apps by profiling binary size on each pull request and surfacing insights and suggestions. Companies using Emerge have reduced the size of their apps by up to 50% in just the first day. Built by a team with years of experience reducing app size at Airbnb.

Set up a demo!

Sponsor Hacking with Swift and reach the world's largest Swift community!

Similar solutions…

Buy Pro Swift Buy Swift Design Patterns Buy Testing Swift Buy Hacking with iOS Buy Swift Coding Challenges Buy Swift on Sundays Volume One Buy Server-Side Swift (Vapor Edition) Buy Advanced iOS Volume One Buy Advanced iOS Volume Two Buy Advanced iOS Volume Three Buy Hacking with watchOS Buy Hacking with tvOS Buy Hacking with macOS Buy Dive Into SpriteKit Buy Swift in Sixty Seconds Buy Objective-C for Swift Developers Buy Server-Side Swift (Kitura Edition) Buy Beyond Code

Was this page useful? Let us know!

Unknown user

You are not logged in

Log in or create account

Link copied to your pasteboard.