我在MacOS应用程序(无Catalyst)的 CountView 视图中计算CoreData ManagedObject Item 的对象数。
第一次直接调用工作正常,第二次在NavigationLists目标中崩溃。
我在做什么错了?
struct ContentView: View {
@Environment(\.managedObjectContext) var moc
@FetchRequest(entity: Item.entity(), sortDescriptors: [], predicate: nil) var items: FetchedResults<Item>
var body: some View {
NavigationView {
VStack {
CountView() // works fine
NavigationLink("Count", destination: CountView()) //crashes
}
}
}
}
struct CountView: View {
@Environment(\.managedObjectContext) var moc
@FetchRequest(entity: Item.entity(), sortDescriptors: [], predicate: nil) var items: FetchedResults<Item>
var body: some View
{ Text("Count: \(items.count) ").frame(maxWidth: .infinity, maxHeight: .infinity)
}
}
在AppDelegate中这样设置上下文:
func applicationDidFinishLaunching(_ aNotification: Notification) {
let moc = persistentContainer.viewContext
let contentView = ContentView().environment(\.managedObjectContext, moc)