使用@fetchRequest(entity:)导致SwiftUI macOS应用崩溃 [英] Using @fetchRequest(entity: ) for SwiftUI macOS app crashes

查看:291
本文介绍了使用@fetchRequest(entity:)导致SwiftUI macOS应用崩溃的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用Core Data为macOS运行基本的测试SwiftUI应用,但遇到了问题.当我在视图中使用它时:

I'm trying to run a basic test SwiftUI app for macOS using Core Data, and I'm hitting a problem. When I use this in my view:

@FetchRequest(entity: Note.entity(), sortDescriptors: []) let notes: FetchedResults<Note>

该应用程序崩溃并出现以下错误:

The app crashes with the following errors:

NoteTaker [error] error: No NSEntityDescriptions in any model claim the NSManagedObject subclass 'NoteTaker.Note' so +entity is confused.  Have you loaded your NSManagedObjectModel yet ?
CoreData: error: No NSEntityDescriptions in any model claim the NSManagedObject subclass 'NoteTaker.Note' so +entity is confused.  Have you loaded your NSManagedObjectModel yet ?

NoteTaker [error] error: +[NoteTaker.Note entity] Failed to find a unique match for an NSEntityDescription to a managed object subclass
CoreData: error: +[NoteTaker.Note entity] Failed to find a unique match for an NSEntityDescription to a managed object subclass

NoteTaker executeFetchRequest:error: A fetch request must have an entity.

现在,如果我使用FetchRequest的替代形式,则尽管代码难看得多,但它仍能正常工作:

Now, if I used the alternate form of FetchRequest, it then works fine though the code is much uglier:

// outside of the view
func getAllNotes() -> NSFetchRequest<Note> {
  let request: NSFetchRequest<Note> = Note.fetchRequest()
  request.sortDescriptors = []
  return request
}

// in the view
@FetchRequest(fetchRequest: getAllNotes()) var notes: FetchedResults<Note>

此外,如果我将其转为iOS应用,则@FetchRequest的实体版本可以正常工作.

Also, if I turn this into an iOS app instead, then the entity version of the @FetchRequest works fine.

有什么想法吗?

推荐答案

使用 Storyboard模板,然后在视图控制器中使用SwiftUI设置视图.

Use the Storyboard template and then set up the view using SwiftUI in the view controller.

override func viewWillAppear() {
        super.viewWillAppear()

        let context = (NSApplication.shared.delegate as! AppDelegate).persistentContainer.viewContext
        let contentView = ContentView().environment(\.managedObjectContext, context)

        view = NSHostingView(rootView: contentView)
    }

这篇关于使用@fetchRequest(entity:)导致SwiftUI macOS应用崩溃的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆