简体   繁体   中英

swiftUI: Changing @State in onAppear crashes

I want to set a @State Variable if a View appears by calling a Service.
Calling the Service in onAppear crashes the app.
Calling the Service in a buttons action works fine.

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

What's going wrong?

the see why this happens, try to modify your code

    var body: some View {
        VStack {
            List {
                ForEach(dirContent, id: \.self){
                    fileName in
                    Text(fileName).onAppear {
                        print("item appear")
                    }
                }
            }.onAppear {
                print("list appear")
            }
            Button("Get Data"){self.dirContent = Service.getData()}
        }
        .onAppear{
            print("content appear")
            DispatchQueue.main.async {
                self.dirContent = Service.getData2()
            }
        }
    }

the "old school" debug print shows us

content appear
list appear
item appear
item appear

Now it is clear, isn't it?

I think I got it. The action has to be called asynchronously.

.onAppear{
  DispatchQueue.main.async {
    self.dirContent = Service.getData2()   
  }
}

Any Idea, why this isn't needed in the buttons action?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM