从 SwiftUI CoreData View 返回计数



我有一个显示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)
}
}
}
}

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

请尝试以下操作

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

最新更新