【问题标题】:return count from a SwiftUI CoreData View从 SwiftUI CoreData 视图返回计数
【发布时间】:2020-02-14 07:49:08
【问题描述】:

我有一个显示 CoreData 查询结果的 SwiftUI 视图。
在它的父视图中,我想显示查询的计数(不再查询一次)。
我试图在绑定中将计数传递给父级,但我收到警告“在视图更新期间修改状态,这将导致未定义的行为。”它不起作用。

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

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

【问题讨论】:

标签: ios core-data swiftui combine


【解决方案1】:

尝试以下方法

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

【讨论】:

  • 如果我的视图需要初始化器 init(c: Binding&lt;Int&gt;) {....},我会收到错误“从初始化器返回而不初始化所有存储的属性”。为什么(以及如何)要初始化绑定
  • @mica,你可以看例子here,或者在SO上搜索其他人。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2021-08-10
  • 2021-05-17
  • 2021-10-10
  • 2020-10-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多