问题描述
如果我在SwiftUI中有一个ObservableObject
,我可以将其称为@ObservedObject
:
If I have an ObservableObject
in SwiftUI I can refer to it as an @ObservedObject
:
class ViewModel: ObservableObject {
@Published var someText = "Hello World!"
}
struct ContentView: View {
@ObservedObject var viewModel = ViewModel()
var body: some View {
Text(viewModel.someText)
}
}
或作为@StateObject
:
class ViewModel: ObservableObject {
@Published var someText = "Hello World!"
}
struct ContentView: View {
@StateObject var viewModel = ViewModel()
var body: some View {
Text(viewModel.someText)
}
}
但是两者之间的实际区别是什么?有没有一种情况比另一种更好,或者它们是两种完全不同的情况?
But what's the actual difference between the two? Are there any situations where one is better than the other, or they are two completely different things?
推荐答案
@ObservedObject
当视图创建自己的@ObservedObject
实例时,每次丢弃并重绘视图时都会重新创建该视图:
When a view creates its own @ObservedObject
instance it is recreated every time a view is discarded and redrawn:
struct ContentView: View {
@ObservedObject var viewModel = ViewModel()
}
相反,当重绘视图时,@State
变量将保留其值.
On the contrary a @State
variable will keep its value when a view is redrawn.
@StateObject
A @StateObject
是@ObservedObject
和@State
的组合-即使丢弃视图并重画视图后,ViewModel
的实例也将保留并重新使用:
A @StateObject
is a combination of @ObservedObject
and @State
- the instance of the ViewModel
will be kept and reused even after a view is discarded and redrawn:
struct ContentView: View {
@StateObject var viewModel = ViewModel()
}
性能
虽然@ObservedObject
会经常迫使View重新创建一个重量级的对象,但会影响性能,但是@ObservedObject
不复杂时,它并不重要.
Although an @ObservedObject
can impact the performance if the View is forced to recreate a heavy-weight object often, it should not matter much when the @ObservedObject
is not complex.
何时使用@ObservedObject
现在看来没有理由使用@ObserverObject
,所以什么时候应该使用它?
It might appear there is no reason now to use an @ObserverObject
, so when should it be used?
请注意,可能有太多用例,有时可能需要来在视图中重新创建可观察的属性.在这种情况下,最好使用@ObservedObject
.
Note there are too many use-cases possible and sometimes it may be desired to recreate an observable property in your View. In that case it's better to use an @ObservedObject
.
有用的链接:
- What’s the difference between @StateObject and @ObservedObject?
- What is the @StateObject property wrapper?
这篇关于SwiftUI中的ObservedObject和StateObject有什么区别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!