Chapters

Hide chapters

SwiftUI Cookbook

Live Edition · iOS 16.4 · Swift 5.8.1 · Xcode 14.3.1

Understanding ObservableObject & ObservedObject
Written by Team Kodeco

In SwiftUI, managing state that’s shared across multiple views requires tools that extend beyond the State property wrapper. This is where ObservableObject and ObservedObject come into play.

ObservableObject is a protocol that SwiftUI provides for objects that can be observed for changes. When you mark a class as conforming to ObservableObject, you’re signaling to SwiftUI that this object’s properties, when changed, should trigger a refresh of any views that depend on them. Any properties marked with @Published in an ObservableObject will automatically notify the view to update when they change.

Let’s see this in action:

class UserSettings: ObservableObject {
  @Published var username = "Anonymous"
}

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

  var body: some View {
    VStack {
      Text("Hello, \(settings.username)!")
      Button("Change Username") {
        settings.username = "John Doe"
      }
    }
  }
}

Your preview should look like this:

Using the ObservedObject and Published property wrappers.
Using the ObservedObject and Published property wrappers.

In this example, UserSettings is an ObservableObject. It has a username property marked with @Published, which means that any changes to username will notify its observers.

ContentView is observing UserSettings via the @ObservedObject property wrapper. When the button is tapped, it changes the username property of settings, which in turn causes the ContentView to update and display the new username.

This interaction between ObservableObject and ObservedObject is fundamental for managing shared state across different views in SwiftUI. It enables you to create a source of truth for your data, which can then be observed and acted upon by any part of your application.

In the following entries, you’ll learn about other state management tools provided by SwiftUI, and how they compare and interact with ObservableObject and ObservedObject.

Have a technical question? Want to report a bug? You can ask questions and report bugs to the book authors in our official book forum here.
© 2024 Kodeco Inc.