Using @fetchRequest(entity: ) for SwiftUI macOS app crashes

天涯浪子 提交于 2020-08-02 08:12:10

问题


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.

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>

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

Any ideas?


回答1:


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)
    }


来源:https://stackoverflow.com/questions/58794088/using-fetchrequestentity-for-swiftui-macos-app-crashes

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!