✅ (1) Understand the difference between
✅ (2) Apply the knowledge to make it possible to edit entries on Yearvu expense tracking app.
For (1), the topic is well summarised in Paul Hudson’s article, What’s the difference between @ObservedObject, @State, and @EnvironmentObject?
@Statefor simple properties that belong to a single view. They should usually be marked private.
@ObservedObjectfor complex properties that might belong to several views. Any time you’re using a reference type you should be using
@EnvironmentObjectfor properties that were created elsewhere in the app, such as shared data.
As for (2), I ran into a problem: I had created the model as a struct, but to use
@ObservedObject I need a reference type. Some refactoring is necessary.
Clearly I cannot use struct as the observed object, but I can create a view model class that can wrap that value and manipulate it accordingly before passing it back.
(Currently editing… ⏱)
Side note: I just found out we can create annotations (officially called property wrappers) in Swift 🤯 Here’s NSHipster’s article showing how.
(Editing continues… ⏱)
- I find out I can create my own property wrappers, which is super cool;
- Apple renamed
ObservedObjectand I could use it to create custom bindings;
- I didn’t find a simple way to provide a bindable object to a form and have it edit it, then save and pass it back to the previous view. I’m considering an approach to have the list of items as a
EnvironmentObjectand each item to be also a
ObservedObject, but I’m still experimenting.