swift - 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 很陌生,所以我什至不知道从哪里开始寻找。这是坏了吗?还是我应该添加更多代码以使其正常工作?有人可以指出正确的方向吗?
解决方案
我在使用 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)
这是一个很小的变化,但现在一切都可以正确编译和运行了。
推荐阅读
- ios - Flutter IOS BackgroundHandler不工作
- c# - UWP 和 WinForm 桌面桥
- python - 如何找到第二个最低有效位数等给定和整数?
- asp.net - IOException:IDX20807:无法从“System.String”检索文档。HttpResponse 消息:
- powerbi - 如何在 Power BI 中使用上下界在柱形图中创建颜色调节
- cmake - 安装 Foonathan 内存依赖项时出错
- javascript - 如何在本机反应中在单个按钮上一一调用多个功能
- snowflake-cloud-data-platform - 雪花中的 ISO 本周迄今
- css - 如何在我的反应 js 页面中应用媒体查询
- python - Pandas:read_csv 读取没有 NaN 的大型 csv 文件