LAST CHANCE: Save 50% on all my Swift books and bundles! >>

How to use @StateObject to create and monitor external objects

Paul Hudson    @twostraws   

Updated for Xcode 13.0

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 {
        NavigationView {
            NavigationLink(destination: PlayerNameView(player: player)) {
                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 project

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

Click here to save 50% on all my books and bundles!

Similar solutions…

BUY OUR BOOKS
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!

Average rating: 5.0/5

 
Unknown user

You are not logged in

Log in or create account
 

Link copied to your pasteboard.