首页 > 解决方案 > SwiftUI + macOS + 基于文档的应用程序问题

问题描述

我正在尝试构建一个启用核心数据的基于文档的 SwiftUI 应用程序。从 Xcode (11.5) 中的模板开始:新建项目 -> macOS + App -> Swift + SwiftUI + “创建基于文档的应用程序” + “使用核心数据”。之后,我尝试在模型编辑器中添加一个只有两个属性“id”和“amount”的实体。该模型称为“Trans”,codegen 设置在“Class Definition”上。

在提供的内容视图中,我添加了下面的代码,以便我可以访问托管对象上下文。

@Environment(\.managedObjectContext) var moc

到目前为止,它按预期工作。之后我尝试添加一个简单的获取请求。

@FetchRequest(entity: Trans.entity(), sortDescriptors: []) var trans: FetchedResults<Trans>

然后这个错误出现在控制台中。

No NSEntityDescriptions in any model claim the NSManagedObject subclass 'myapp.Trans' so +entity is confused. Have you loaded your NSManagedObjectModel yet?

我对 Core Data 很陌生,所以我什至不知道从哪里开始寻找。这是坏了吗?还是我应该添加更多代码以使其正常工作?有人可以指出正确的方向吗?

标签: swiftxcodecore-dataswiftui

解决方案


我在使用 Xcode12(Beta 2)和多平台选项创建应用程序时遇到了这个确切的问题。

有效的方法是将代码分开,以便在您尝试使用它之前完全初始化您的上下文。

所以取下面这行代码,拆分成两行代码:

// Create the SwiftUI view and set the context as the value for the managedObjectContext environment keyPath.
// Add `@Environment(\.managedObjectContext)` in the views that will need the context.
let contentView = ContentView().environment(\.managedObjectContext, persistentContainer.viewContext)

将其分为两行:

// Create the SwiftUI view and set the context as the value for the managedObjectContext environment keyPath.
// Add `@Environment(\.managedObjectContext)` in the views that will need the context.
let context = persistentContainer.viewContext
let contentView = ContentView().environment(\.managedObjectContext, context)

这是一个很小的变化,但现在一切都可以正确编译和运行了。


推荐阅读