【发布时间】:2020-03-12 22:17:11
【问题描述】:
如果视图通过调用服务出现,我想设置一个@State 变量。
在onAppear 中调用服务会使应用程序崩溃。
在按钮操作中调用服务可以正常工作。
struct ContentView: View {
@State var dirContent : [String] = []
var body: some View {
VStack {
List {
ForEach(dirContent, id: \.self){
fileName in
Text(fileName)
}
}
Button("Get Data"){self.dirContent = Service.getData()}
}
.onAppear{
//self.dirContent = Service.getData2() // Crashes!!
}
}
}
class Service{
static func getData()->[String]{
// ... get Data from somewhere
return ["line1", "line2"]
}
static func getData2()->[String]{
// ... get Data from somewhere
return ["line4", "line5"]
}
}
怎么了?
【问题讨论】: