NEW: Join my free 100 Days of SwiftUI challenge today! >>

What is the @ObservedObject property wrapper?

Paul Hudson    @twostraws   

Fully updated for Xcode 11.2

SwiftUI gives us the @ObservedObject property wrapper so that views can watch the state of an external object, and be notified when something important has changed.

For example, we might use something like this:

class Order: ObservableObject {
    @Published var items = [String]()
}

struct ContentView: View {
    @ObservedObject var order = Order()

    var body: some View {
        // your code here
    }
}

That Order class uses @Published so it will automatically send change announcements when items changes, and ContentView uses @ObservedObject to watch for those announcements. Without @ObservedObject the change announcements would be sent but ignored.

Although that looks straightforward enough, it’s worth digging into a few specifics.

First, any type you mark with @ObservedObject must conform to the ObservableObject protocol, which in turn means it must be a class rather than a struct. This isn’t optional – SwiftUI requires us to use a class here.

Second, observed objects are specifically designed for data that is external to your view, which means it might be shared across more than one view. The @ObservedObject property wrapper will automatically make sure the property is watched closely so that important changes will reload any views using it.

Third, not all properties in an observed object cause views to refresh – you need to decide which properties should send change notifications, either using @Published or custom announcements. Types that conform to ObservableObject are given a default objectWillChange publisher to make custom announcements as needed.

SPONSORED Instabug helps you identify and resolve severe crashes quickly. You can retrace in-app events and know exactly which line of code caused the crash along with environment details, network logs, repro steps, and the session profiler. Ask more questions or keep users up-to-date with in-app replies straight from your dashboard. Instabug takes data privacy seriously, so no one sees your data but you! See more detailed features comparison and try Instabug's crash reporting SDK for free.

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!