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

What is the @StateObject property wrapper?

Paul Hudson    @twostraws   

Updated for Xcode 12.5

New in iOS 14

SwiftUI’s @StateObject property wrapper is designed to fill a very specific gap in state management: when you need to create a reference type inside one of your views and make sure it stays alive for use in that view and others you share it with.

As an example, consider a simple User class such as this one:

class User: ObservableObject {
    var username = "@twostraws"
}

If you want to use that inside various views, you either need to create it externally to SwiftUI and inject it in, or create it inside one of your SwiftUI views and use @StateObject, like this:

struct ContentView: View {
    @StateObject var user = User()

    var body: some View {
        Text("Username: \(user.username)")
    }
}

That will make sure the User instance does not get destroyed when the view updates.

Previously you might have used @ObservedObject to get the same result, but that was dangerous – sometimes, and only sometimes, @ObservedObject could accidentally release the object it was storing, because it wasn’t designed to be the ultimate source of truth for the object. This won’t happen with @StateObject, so you should use it instead.

Important: You should use @StateObject only once per object, which should be in whichever view is responsible for creating the object. All other views that share your object should use @ObservedObject.

Hacking with Swift is sponsored by Instabug

SPONSORED Catch bugs as soon as they happen and know exactly why a crash occurred. Instabug's SDK grabs all the logs they need to fix bugs, crashes and performance issues in minutes instead of days. Get screenshots, device details, network logs, repro steps, and tons of other critical insights needed to resolve issues and prioritize product backlogs straight from your dashboard. It only takes a minute to integrate!

Get started now

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

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: 3.9/5

 
Unknown user

You are not logged in

Log in or create account
 

Link copied to your pasteboard.