NEW: Learn SwiftUI with my free YouTube video series! >>

< What’s the difference between @ObservedObject, @State, and @EnvironmentObject?   How to send state updates manually using objectWillChange >

How to use @ObservedObject to manage state from external objects

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 a bindable 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.

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

class UserSettings: 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 UserSettings class inside a view like this:

struct ContentView: View {
    @ObservedObject var settings = UserSettings()

    var body: some View {
        VStack {
            Text("Your score is \(settings.score)")
            Button(action: {
                self.settings.score += 1
            }) {
                Text("Increase Score")
            }
        }
    }
}

As you can see, other than using the @ObservedObject property wrapper with settings, 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 settings 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.

SPONSOR Meet the new Instabug – more than just bug reporting! We help you build better apps and minimize your debugging time. With each bug report, we automatically capture details like network requests, repro steps, and session details. Get real-time crash reports with stack trace details and session data to help you catch and fix issues easily. And with our customizable in-app surveys, you’ll gather insightful user feedback and much more. Instabug is the fastest and easiest way to release with confidence. Start your free trial now! Start your free trial now!

< What’s the difference between @ObservedObject, @State, and @EnvironmentObject?   How to send state updates manually using objectWillChange >
MASTER SWIFT NOW
Buy Testing Swift Buy Practical iOS 12 Buy Pro Swift Buy Swift Design Patterns Buy Swift Coding Challenges Buy Server-Side Swift (Vapor Edition) Buy Server-Side Swift (Kitura Edition) Buy Hacking with macOS Buy Advanced iOS Volume One Buy Advanced iOS Volume Two Buy Hacking with watchOS Buy Hacking with tvOS Buy Hacking with Swift Buy Dive Into SpriteKit Buy Swift in Sixty Seconds Buy Objective-C for Swift Developers Buy Beyond Code

Was this page useful? Let me know!

Average rating: 5.0/5

Click here to visit the Hacking with Swift store >>