macOS文档应用程序SwiftUI项目上的NSPersistentDocument FetchRequest warp属性崩溃 使用Xcode macOS文档应用程序模板创建项目,选中使用核心数据复选框 将书本实体添加到文档.xcdatamodeld 将FetchRequest warp属性添加到ContentView @FetchRequest(实体:Book.entity(),sortDescriptors:[])var books:FetchedResults 构建并运行,崩溃

macOS文档应用程序SwiftUI项目上的NSPersistentDocument FetchRequest warp属性崩溃 使用Xcode macOS文档应用程序模板创建项目,选中使用核心数据复选框 将书本实体添加到文档.xcdatamodeld 将FetchRequest warp属性添加到ContentView @FetchRequest(实体:Book.entity(),sortDescriptors:[])var books:FetchedResults 构建并运行,崩溃,macos,swiftui,nspersistentdocument,fetchrequest,Macos,Swiftui,Nspersistentdocument,Fetchrequest,控制台中的崩溃日志为 2020-07-03 23:12:23.597880+0800 DocMacDemo[15236:4376209][error]错误:任何模型中都没有NSEntityDescriptions声称NSManagedObject子类“DocMacDemo.Book”so+实体混淆。您已经加载了NSManagedObjectModel吗? CoreData:错误:任何模型中都没有NSEntityDescriptions声明NSManagedObject子类“DocMacDemo.

控制台中的崩溃日志为

2020-07-03 23:12:23.597880+0800 DocMacDemo[15236:4376209][error]错误:任何模型中都没有NSEntityDescriptions声称NSManagedObject子类“DocMacDemo.Book”so+实体混淆。您已经加载了NSManagedObjectModel吗?
CoreData:错误:任何模型中都没有NSEntityDescriptions声明NSManagedObject子类“DocMacDemo.Book”so+实体混淆。您已经加载了NSManagedObjectModel吗?
2020-07-03 23:12:23.598287+0800 DocMacDemo[15236:4376209][error]错误:+[DocMacDemo.Book entity]未能找到NSEntityDescription与托管对象子类的唯一匹配项
CoreData:错误:+[DocMacDemo.Book entity]未能找到NSEntityDescription与托管对象子类的唯一匹配项
2020-07-03 23:12:23.644491+0800 DocMacDemo[15236:4376209]executeFetchRequest:错误:获取请求必须具有实体。
2020-07-03 23:12:23.653769+0800 DocMacDemo[15236:4376209][error]错误:获取请求的实体0x60000350420“Book”似乎来自与此上下文不同的NSManagedObjectModel
CoreData:错误:获取请求的实体0x60000350420“Book”似乎来自与此上下文不同的NSManagedObjectModel
(lldb)
我已经找了好几天NSPersistentDocument SwiftUI示例,但找不到一个。 这里有一些相似或相关的问题。不幸的是,这个问题没有得到解决

编辑:
将此问题项目上载到Github。

这是由于新文档为空。与任何基于文档的应用程序一样,您必须为新文档准备一些默认初始数据

这是可能的解决办法。使用Xcode 11.4/iOS 13.4进行测试

在.swift文件中

class Document: NSPersistentDocument {

    // .. other code here

    override func makeWindowControllers() {

        // in case of new document create new empty book in context
        // that will be shown in opened document window
        let isNew = self.fileURL == nil
        if isNew {
            _ = Book(context: self.managedObjectContext!)       // << here !!
        }

        let contentView = ContentView().environment(\.managedObjectContext, self.managedObjectContext!)

        // ... other code here
类文档:NSPersistentDocument{
//…这里还有其他代码
重写func makeWindowController(){
//如果是新文档,请在上下文中创建新的空白图书
//这将显示在打开的文档窗口中
让isNew=self.fileURL==nil
如果是新的{

_=Book(context:self.managedObjectContext!)//好吧,Asperi的答案很好,但这会在对象模型中留下一本可能不需要的书。另一种方法是将上下文保存在Asperi建议的相同位置:

    if let context = managedObjectContext {
        try? context.save()
    }
然后,FetchRequest也不会出现错误消息