SwiftUI ViewModel 永远保持 init

问题描述 投票:0回答:1

我有这样的结构。

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")
        }
    }
}

一旦我更改了设置参数的值,两个视图模型将永远重复初始化,并且似乎只有当我将

ContentView
放入
FatherView
并在

中声明设置的@StateObject时才会发生这种情况
ios swift swiftui viewmodel
1个回答
0
投票

这似乎是正确的,因为当您初始化

ViewModel
AnotherViewModel
时,您还设置了
Settings.shared
值,该值绑定到
FatherView
。这是循环的原因。

FatherView -> get ContentView -> init ViewModel -> Setting.shared -> get Content -> Loop...
© www.soinside.com 2019 - 2024. All rights reserved.