My understanding is that the key differences between @ObservedObject and @StateObject relates to ownership of the object and how likely it is for the object to be recreated.
For example, if you have a view that creates an @ObservedObject var test = Test(), every time that view is redrawn (which might be many times), it will recreate a new instance of Test. If you have a view that takes an @ObservedObject as an initialized property like
Code Block | struct Tester: View { |
| @ObservedObject var test: Test |
|
| var body: some View { |
| ... |
| } |
| } |
Then the test instance won't be recreated each time the Tester view is redrawn, but you're then dependent on whatever view owns the Test object to hold onto it.
@StateObject avoids much of those issues.
Code Block | struct Tester: View { |
| @StateObject var test = Test() |
|
| var body: some View { |
| ... |
| } |
| } |
In that example, @StateObject tells SwiftUI to hold onto the value of test, even if the view is redrawn repeatedly.