使用@fetchRequest(entity:)导致SwiftUI macOS应用崩溃

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

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

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

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的替代形式,则尽管代码丑陋得多,但它仍然可以正常工作:

// 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的实体版本可以正常工作。

有什么想法吗?

ks_xpd 回答:使用@fetchRequest(entity:)导致SwiftUI macOS应用崩溃

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

override func viewWillAppear() {
        super.viewWillAppear()

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

        view = NSHostingView(rootView: contentView)
    }
,

添加此行: .environment(.managedObjectContext,context)

在SceneDelegate.swift中

at

// 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,context)
,

在获取和动态获取请求以及创建核心数据对象的代码中的多个地方出现此错误,这对我有用:

在获取请求期间,我使用了此

@FetchRequest(entity: NSEntityDescription.entity(forEntityName: "Your Entity Name",in: managedObjectContext),sortDescriptors: [NSSortDescriptor(key: "Your Key",ascending: true)])

在动态提取请求中,我使用了以下方法:

var entity: Entity
var fetchRequest: FetchRequest<Your Entity>
init(_ entity: Entity) {
self.entity = entity
self.fetchRequest = FetchRequest(entity: NSEntityDescription.entity(forEntityName: "Your Entity",ascending: true)],predicate: NSPredicate(format: "entity.uniqueIdentifier == %@",entity.uniqueIdentifier!))
}

var youEntities: FetchedResults<Your Entity> {
fetchRequest.wrappedValue
}

创建核心数据对象时:

let entityDescription = NSEntityDescription.entity(forEntityName: "Your Entity",in: managedObjectContext)

let object = Your Entity(entity: entityDescription!,insertInto: managedObjectContext)
本文链接:https://www.f2er.com/3127107.html

大家都在问