首页 > 解决方案 > SwiftUI - 如何正确重新加载 @ObservableObject 对象

问题描述

我已经开始将我的应用程序 [RsyncOSX][1] 重写为 SwiftUI(需要学习很多东西)。配置和时间表是从永久存储中读取的,这很好。以下代码完成了这项工作:

import SwiftUI

struct Readdatafromstore {
    var profile: String?
    var configurationData: ConfigurationsSwiftUI
    var validhiddenIDs: Set<Int>
    var scheduleData: SchedulesSwiftUI

    init(profile: String?) {
        self.profile = profile
        self.configurationData = ConfigurationsSwiftUI(profile: self.profile)
        self.validhiddenIDs = self.configurationData.getvalidhiddenIDs() ?? Set()
        self.scheduleData = SchedulesSwiftUI(profile: self.profile, validhiddenIDs: self.validhiddenIDs)
    }
}
final class RsyncOSXdata: ObservableObject {
    @Published var rsyncdata: Readdatafromstore?
    @Published var configurations: [Configuration]?
    @Published var schedulesandlogs: [ConfigurationSchedule]?
    @Published var arguments: [ArgumentsOneConfiguration]?
    init(profile: String?) {
        self.rsyncdata = Readdatafromstore(profile: profile)
        self.configurations = self.rsyncdata?.configurationData.getconfigurations() ?? []
        self.schedulesandlogs = self.rsyncdata?.scheduleData.getschedules() ?? []
        self.arguments = self.rsyncdata?.configurationData.getarguments() ?? []
    }
}

视图加载了以下内容:

let contentView = ContentView().environmentObject(RsyncOSXdata(profile: "profilename"))

视图通过以下方式读取数据

@EnvironmentObject private var rsyncOSXData: RsyncOSXdata

配置由配置文件存储,问题是:如何重新加载@ObservableObject?默认配置文件在开始时被读取和加载。

重新加载@ObservableObject对象不会更新视图...

解决了

contentView 的调用发生了变化,调用侧边栏功能时设置了 environmentObject ..

let contentView = ContentView()
...
window.contentView = NSHostingView(rootView: contentView)

和内容视图():

struct ContentView: View {
    @State private var selectedprofile: String?
    var profiles: [String]? {
        return Catalogsandfiles(profileorsshrootpath: .profileroot).getcatalogsasstringnames()
    }

    var body: some View {
        VStack {
            Picker("Profile: ", selection: $selectedprofile) {
                ForEach(0 ..< (profiles?.count ?? 0)) {
                    Text(self.profiles?[$0] ?? "").tag(self.profiles?[$0])
                }
            }
            SidebarNavigation().environmentObject(RsyncOSXdata(profile: selectedprofile))
            Text(selectedprofile ?? "Default")
        }
    }
}

选择一个新的配置文件现在会自动更新视图,因为它们应该是。我现在不知道为什么更改解决了这个问题,但它有效.. [1]:https ://github.com/rsyncOSX/RsyncOSX

标签: swiftuiobservers

解决方案


推荐阅读