SwiftUI_visionOS_Note

@StateObject & @ObservableObject

Apr 29, 2024
@StateObject & @ObservableObject
  • Property wrapper to observe other classes, and have them updated in view
  • Update current view when something gets updated in other classses.
 

1. Set up

a. Create a navigation Stack

b. custom data type

Now fruit model has string id, name and count

 

c. Create an array of fruit model

 

d. add data into List

inside the Hstatck text will bring the data from the fruitArray

 

e. onAppear function

 

f. onDelete

 

2. Create a custom class to hold extra data

 

a. Create a class outside of current View

  • @Published works same as state.
 

b. import the class into a current View

 

c. bring the fruitArray function into the class

 

d. change the fruitArray → fruitViewModel.data or fruitViewModel.function

 
Callout icon'
But, we can not still see the updated data in our view

e. Add @ObservedObejct on fruitViewModel & @ObservableObejct on FruitViewModel

 

f. Add isLoading

 
 
 

3. @StateObject

Why is important?

  • Whenever the view get updated and reloaded, @ObservedObject also gets reloaded. When user wants to reload the page but data should be remained, @StateObject is persist.

→ @StateObject → INIT

→ @ObservedObejct → Subview

 

a. Create a Random Screen

 
 

C. delete onAppear and create a custom init() in FruitViewModel

 
 

d. Change the random screen to have array of fruitviewmodel

 
 
 
 
 

Today, I learned about ObservableObject

and StateObject. These are property

wrappers that observe other classes

and update them in the view.

 

Whenever the view is updated and

reloaded, @ObservedObject also gets

reloaded. If you want to reload the

page but keep the data intact,

@StateObject is preferred.

 

You can use the custom dataset

from current view or in another view.

This way, you can update the dataset

and preserve the data when transitioning

to a different view with their data set.

 
 
 

#visionOS #AppleVisionPro #VisionPro #SpatialApp #SwiftUI #AppDevelopment

 

You might also like

BlogPro logo
Made with BlogPro