Использование @fetchRequest(entity:) для SwiftUI в приложении macOS дает сбой

Я пытаюсь запустить базовое тестовое приложение SwiftUI для macOS с использованием Core Data, и у меня возникает проблема. Когда я использую это на мой взгляд:

@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 будет работать нормально.

Есть идеи?

2 ответа

Я получал эту ошибку в нескольких местах моего кода для запросов на выборку и динамическую выборку, а также при создании основных объектов данных это то, что у меня сработало:

Во время запросов на выборку я использовал это:

@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", in: managedObjectContext), sortDescriptors: [NSSortDescriptor(key: "Your Key", 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)

Добавление этой строки: .environment(.managedObjectContext, context)

в SceneDelegate.swift

в

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

Используйте шаблон раскадровки, а затем настройте представление с помощью 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)
    }
Другие вопросы по тегам