0

我的 SwiftUI 项目中有这段代码运行良好

struct ContentView: View {

@State private var selectedCountry: Country?
@State private var showSetting = false

@FetchRequest(entity: Country.entity(),
              sortDescriptors: [NSSortDescriptor(keyPath: \Country.cntryName, ascending: true)]
) var countries: FetchedResults<Country>

var body: some View {
    NavigationView {
        VStack {
            Form {
                Picker("Pick a country", selection: $selectedCountry) {
                    ForEach(countries, id: \Country.cntryName) { country in
                        Text(country.cntryName ?? "Error").tag(country as Country?)
                    }
                }
                if selectedCountry != nil {
                    DetailView(cntryName: (selectedCountry?.cntryName!)!)
                }
            }
        }
        .navigationBarTitle("UNECE Data")
        .navigationBarItems(trailing: Button("Settings", action: {
            self.showSetting.toggle()
        }))
    }
    .sheet(isPresented: $showSetting) {
        SettingsView(showSetting: self.$showSetting)
    }
}
}

但是,当 SettingsView 关闭时,我需要动态调用 FetchRequest 结束重新加载 Picker 视图。可能我应该使用@ObservableObject,但是如何在 Picker 视图 ForEach 中放置获取请求并使用结果?感谢您的提示。

4

3 回答 3

1

您可以自定义 FetchRequest 的大部分内容:

@FetchRequest(entity: Country.entity(),
          sortDescriptors:  ObservableObject.sortDesc,
          predicate : ObservableObject.predicate
  ) var countries: FetchedResults<Country>
于 2020-02-22T19:13:43.973 回答
0

我已经修改了这样的代码

var body: some View {
    NavigationView {
        VStack {
            Form {
                //Text(String(describing: countries.count))
                Picker("Pick a country", selection: $selectedCountry) {
                    ForEach(getAllCountries().wrappedValue, id: \Country.cntryName) { country in
                        Text(country.cntryName ?? "Error").tag(country as Country?)
                    }
                }
                if selectedCountry != nil {
                    DetailView(cntryName: (selectedCountry?.cntryName!)!)
                }
            }
        }
        .navigationBarTitle("UNECE Data")
        .navigationBarItems(trailing: Button("Settings", action: {
            self.showSetting.toggle()
        }))
    }
    .sheet(isPresented: $showSetting) {
        SettingsView(showSetting: self.$showSetting)
    }
}

func getAllCountries() -> FetchRequest<Country> {
    let request = FetchRequest<Country>(entity: Country.entity(),
                  sortDescriptors: [NSSortDescriptor(keyPath: \Country.cntryName, ascending: true)])
    return request
}

但它在运行时在 ForEach 行上报告致命错误“线程 1:EXC_BAD_INSTRUCTION (code=EXC_I386_INVOP, subcode=0x0)”。

于 2020-02-22T21:49:11.193 回答
0

在 SettingsView 我删除 Country 实体中的所有数据,解析存储在我的 iCloud 上的 JSON 文件并将所有数据保存在 Country 实体中。

于 2020-02-23T15:36:49.707 回答