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

How to use @ObservedObject to manage state from external objects

Paul Hudson    @twostraws   

Updated for Xcode 12.5

When using observed objects there are three key things we need to work with: the ObservableObject protocol is used with some sort of class that can store data, the @ObservedObject property wrapper is used inside a view to store an observable object instance, and the @Published property wrapper is added to any properties inside an observed object that should cause views to update when they change.

Tip: It is really important that you use @ObservedObject only with views that were passed in from elsewhere. You should not use this property wrapper to create the initial instance of an observable object – that’s what @StateObject is for.

As an example, here’s a UserProgress class that conforms to ObservableObject:

class UserProgress: ObservableObject {
    @Published var score = 0
}

I know that doesn’t look like much code, but that’s because SwiftUI is doing a remarkable amount on our behalf! There are two things that matter in there:

  1. The ObservableObject conformance allows instances of this class to be used inside views, so that when important changes happen the view will reload.
  2. The @Published property wrapper tells SwiftUI that changes to score should trigger view reloads.

We can use that UserProgress class with code like this:

class UserProgress: ObservableObject {
    @Published var score = 0
}

struct InnerView: View {
    @ObservedObject var progress: UserProgress

    var body: some View {
        Button("Increase Score") {
            progress.score += 1
        }
    }
}

struct ContentView: View {
    @StateObject var progress = UserProgress()

    var body: some View {
        VStack {
            Text("Your score is \(progress.score)")
            InnerView(progress: progress)
        }
    }
}

As you can see, other than using the @ObservedObject property wrapper with progress, everything else more or less looks the same – SwiftUI takes care of all the implementation details for us.

There is one important difference, though: the progress property isn’t declared as private. This is because bound objects can be used by more than one view, so it’s common to share it openly.

Remember, please do not use @ObservedObject to create instances of your object. If that’s what you want to do, use @StateObject instead.

Hacking with Swift is sponsored by ViRE

SPONSORED ViRE offers discoverable way of working with regex. It provides really readable regex experience, code complete & cheat sheet, unit tests, powerful replace system, step-by-step search & replace, regex visual scheme, regex history & playground. ViRE is available on Mac & iPad.

Download on the App Store

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

 
Unknown user

You are not logged in

Log in or create account
 

Link copied to your pasteboard.