mica
mica

Reputation: 4308

return count from a SwiftUI CoreData View

I have a SwiftUI view that displays the result of a CoreData query.
In it's parent view I want to display the count of the query (without querying one more time).
I tried to pass the count to the parent in a Binding, but I get the warning "Modifying state during view update, this will cause undefined behavior." an it does not work.

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)
      }
    }
  }
}

Any ideas how to set the Binding correctly or how else to pass the count to the parent?

Upvotes: 1

Views: 2175

Answers (1)

Asperi
Asperi

Reputation: 257583

Try instead the following

  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)
      }
    }
  }

Upvotes: 4

Related Questions