I have the structure like this.
import SwiftUI
//create a simple view model
class ViewModel: NSObject, ObservableObject {
@Published var name: String = "World"
//create a reference of another viewmodel
let anotherViewModel = AnotherViewModel()
override init() {
super.init()
print("init")
Settings.shared.test = "2"
}
}
//create another view model
class AnotherViewModel: ObservableObject {
@Published var name: String = "World"
init(){
print("another init")
Settings.shared.test = "3"
}
}
//create singleton with a bool
class Settings: ObservableObject {
static let shared = Settings()
@Published var isShow: Bool = false
@Published var test = "1"
}
struct FatherView: View {
@StateObject var settings = Settings.shared//if I remove this line, it will be normal.
var body:some View{
ContentView()
}
}
struct ContentView: View {
//@StateObject var settingsHolder = Settings.shared
@StateObject var model: ViewModel
@StateObject var model1: AnotherViewModel
init() {
let model = ViewModel()
_model = StateObject(wrappedValue: model)
_model1 = StateObject(wrappedValue: model.anotherViewModel)
}
var body: some View {
VStack {
Text("Hi")
}
}
}
Once I change the value of settings parameters, the two view model will repeat init forever, and it seems only happen when I put the ContentView
into FatherView
and declare the @StateObject of settings in the