开发 macOS 应用程序, 想在 MenuBarExtra 里访问 CoreData:
struct Project: App {
@StateObject private var dataController = DataController()
@FetchRequest(sortDescriptors: []) var students: FetchedResults<Student>
var body: some Scene {
MainScene()
Settings { Text("Setting") }
MenuBarExtra("Menu", systemImage: "swift") {
List(students) { student in
Text(student.name ?? "Unknown")
}
Divider()
Button("Add") {
let id = UUID()
let name = "Foo"
let context = dataController.container.viewContext
let student = Student(context: context)
student.id = id
student.name = name
try? context.save()
}
}
}
}
我刚接触 CoreData, 参照 hackingwithswift 的例子, 它是将 viewContext
传递给 enviroment
中, 所以在 ContentView 里面都可以直接访问 @Environment(\.managedObjectContext) var moc
.
但在 MenuBarExtra
中不知道如何处理, 无法注入 context, 并且当我按照上述例子中直接使用 context 时候编译器会报错:
Context in environment is not connected to a persistent store coordinator.
1
FaiChou OP |