From the course: Complete Guide to SwiftUI

Unlock this course with a free trial

Join today to access over 24,600 courses taught by industry experts.

Create observable objects in models

Create observable objects in models

From the course: Complete Guide to SwiftUI

Create observable objects in models

- [Instructor] We've looked at a read-only model and simple objects using @Binding and @State. There's a problem with using @Binding and an @State for a model. Not all your data changes trigger a state change and a redraw of a view. There'd be a huge overhead to monitor all properties of a model. This is where you use ObservableObjects. ObservableObject is a protocol you can add to a class used for a model, specifying at least one property that triggers a redraw. Notice you are using classes and not structs here. For models we want to reference class for the most efficient model, and sometimes the only way to get a model to work. We loaded the Model Code folder, a file called OrderModel. So we can take a look at that one right over here. This uses the order item we used previously and makes a collection of them that is a single order. Now, your first step is adopting the ObservableObject protocol on your class. So we can go into here in an OrderModel, and I just have to adopt the…

Contents