NEW: My new book Pro SwiftUI is out now – level up your SwiftUI skills today! >>

How to use @StateObject to create and monitor external objects

Paul Hudson    @twostraws   

Updated for Xcode 14.2

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, \(!")

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

Hacking with Swift is sponsored by Waldo

SPONSORED Thorough mobile testing hasn’t been efficient testing. With Waldo Sessions, it can be! Test early, test often, test directly in your browser and share the replay with your team.

Try for free today!

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

Similar solutions…

Buy Pro Swift Buy Pro SwiftUI 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 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 Beyond Code

Was this page useful? Let us know!

Average rating: 4.6/5

Unknown user

You are not logged in

Log in or create account

Link copied to your pasteboard.