Skip to main content

How to use @StateObject to create and monitor external objects

About 2 minSwiftSwiftUIArticle(s)bloghackingwithswift.comcrashcourseswiftswiftuixcodeappstore

How to use @StateObject to create and monitor external objects 관련

SwiftUI by Example

Back to Home

How to use @StateObject to create and monitor external objects | SwiftUI by Example

How to use @StateObject to create and monitor external objects

Updated for Xcode 15

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 find 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 Player: ObservableObject {
    @Published var name = "Taylor"
    @Published var age = 26
}

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

    var body: some View {
        NavigationStack {
            NavigationLink {
                PlayerNameView(player: player)
            } label: {
                Text("Show detail view")
            }
        }
    }
}

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

    var body: some View {
        Text("Hello, \(player.name)!")
    }
}

Download this as an Xcode projectopen in new window

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.”

Similar solutions…
How to use @ObservedObject to manage state from external objects | SwiftUI by Example

How to use @ObservedObject to manage state from external objects
What is the @StateObject property wrapper? | SwiftUI by Example

What is the @StateObject property wrapper?
Observable objects, environment objects, and @Published | SwiftUI by Example

Observable objects, environment objects, and @Published
All SwiftUI property wrappers explained and compared | SwiftUI by Example

All SwiftUI property wrappers explained and compared
SwiftUI tips and tricks | SwiftUI by Example

SwiftUI tips and tricks

이찬희 (MarkiiimarK)
Never Stop Learning.