SwiftUI中的EnvironmentObject vs Singleton? [英] EnvironmentObject vs Singleton in SwiftUI?
问题描述
如果整个视图在应用程序中访问同一模型,则我认为Singleton模式就足够了.我说的对吗?
If the entire views access the same model in an app, I think the Singleton pattern is enough. Am I right?
例如,如果MainView和ChildView访问相同的模型(例如AppSetting),如下所示,我找不到使用EnvironmentObject而不是Singleton模式的任何理由. 如果我这样使用是否有问题?如果可以,那么什么时候应该使用EnvironmentObject而不是Singleton模式?
For example, if MainView and ChildView access the same model(e.g. AppSetting) like below, I cannot find any reason to use EnvironmentObject instead of the Singleton pattern. Is there any problem if I use like this? If it is okay, then when I should use EnvironmentObject instead of the Singleton pattern?
class AppSetting: ObservableObject {
static let shared = AppSetting()
private init() {}
@Published var userName: String = "StackOverflow"
}
struct MainView: View {
@ObservedObject private var appSetting = AppSetting.shared
var body: some View {
Text(appSetting.userName)
}
}
struct ChildView: View {
@ObservedObject private var appSetting = AppSetting.shared
var body: some View {
Text(appSetting.userName)
}
}
谢谢.
推荐答案
您是正确的,在这种情况下没有理由使用EnvironmentObject.苹果甚至鼓励不要过度使用EnvironmentObject.
You are correct there is no reason in this case to use an EnvironmentObject. Apple even encourages to make no excessive use of EnvironmentObject.
尽管如此,如果您在多个视图中使用对象,EnvironmentObject也可以很棒,因为这样您就不必将其从视图A传递到视图B,从视图B传递到视图C,依此类推.
Nevertheless EnvironmentObject can be great too, if you use an object in many views, because then you don't have to pass it from View A to B, from B to C and so on.
通常您会发现自己处于这样一种情况,即使@State和@Binding也足以在一个视图中以及两个视图之间共享和更新数据.
Often you find yourself in a situation where even @State and @Binding will be enough to share and update data in a view and between two views.
这篇关于SwiftUI中的EnvironmentObject vs Singleton?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!