1

编辑添加了显示变量声明的源代码

我正在尝试初始化一个视图模型属性,它是一个 @ObservedObject @ObservedObject private var viewmodel : ExpenseListViewModel

我想使用存储库初始化视图模型,该存储库将接受 ManagedObjectContext 作为构造函数中的参数

由于 viewmodel 有一个 prperty 包装器,因此也不允许将其创建为计算属性。

当我尝试在 init 中初始化存储库和视图模型时,我在初始化之前使用了一个 self

struct ContentView: View {
    @Environment(\.managedObjectContext) private var moc
    private (set) var repo: Repository
    @ObservedObject  private var viewmodel : ExpenseListViewModel 
    init() {
        //let repository = CoreDataRepository(Context: moc)
        repo = CoreDataRepository(Context: self.moc)
        self.viewmodel = .init(repository: repo)
    }
    var body: some View {
        Text(viewmodel.Expenses[0].Name ).onAppear(perform: viewmodel.getExpenses )
    }
}
4

1 回答 1

2

@Environmentinit 调用阶段不可用,稍后注入。所以这是可能的解决方案:

struct ContentView: View {
    @Environment(\.managedObjectContext) private var moc

    var body: some View {
        InternalContentView(context: moc) // context is ready in body
    }

    struct InternalContentView: View {
        @ObservedObject private var viewmodel: ExpenseListViewModel

        init(context: NSManagedObjectContext) {
            self.viewmodel = .init(repository: CoreDataRepository(Context: context))
        }

        var body: some View {
            Text(viewmodel.Expenses[0].Name ).onAppear(perform: viewmodel.getExpenses )
        }
    }
}
于 2020-08-03T05:10:14.390 回答