return 从 SwiftUI CoreData 视图计数

return count from a SwiftUI CoreData View

我有一个显示 CoreData 查询结果的 SwiftUI 视图。
在它的父视图中,我想显示查询的计数(不再查询一次)。
我试图在绑定中将计数传递给父级,但我收到警告 "Modifying state during view update, this will cause undefined behavior." 它不起作用。

import SwiftUI

struct CD_Main: View {
  @State var count = 0

    var body: some View {
      VStack {
        Text("count in main: \(count)")
        CD_Query(c: $count)
      }
    }
}

struct CD_Query: View {
  @Binding var c : Int

  @Environment(\.managedObjectContext) var moc
  @FetchRequest(entity: Item.entity(), sortDescriptors: [], predicate: nil) var items: FetchedResults<Item>

  var body: some View {
  c = items.count // Produces: Modifying state during view update, this will cause undefined behavior.
    return VStack {
      Text("Count Innen: \(items.count) ")
      List(items, id: \.self) {
        item in
        Text(item.title)
      }
    }
  }
}

关于如何正确设置绑定或如何将计数传递给父项的任何想法?

试试下面的方法

  var body: some View {
    VStack {
      Text("Count Innen: \(items.count) ")
      .onAppear { // actually it does not matter to which view this attached
         DispatchQueue.main.async {
            self.c = items.count // update asynchronously
         }
      }
      List(items, id: \.self) {
        item in
        Text(item.title)
      }
    }
  }