1
votes

I am trying to build a document based SwiftUI application with core data enabled. Starting from the template in Xcode (11.5): New project -> macOS + App -> Swift + SwiftUI + "Create document-based application" + "Use Core data". After that I try to add an entity in model editor with just two attributes, "id" and "amount". The model is called "Trans" and codegen is set on "Class Definition".

In the provided Content view I add the code below so I can access the managed object context.

@Environment(\.managedObjectContext) var moc

So far it's working as expected. After that I try to add a simple fetch request.

@FetchRequest(entity: Trans.entity(), sortDescriptors: []) var trans: FetchedResults<Trans>

Then this error comes up in the console.

No NSEntityDescriptions in any model claim the NSManagedObject subclass 'myapp.Trans' so +entity is confused. Have you loaded your NSManagedObjectModel yet?

I am quite new to Core Data so I don't even know where to start looking. Is this broken? Or am I supposed to add more code to get it to work? Can someone please point in the right direction?

1

1 Answers

0
votes

I had this exact problem creating an app using Xcode12 (Beta 2) and the multi-platform option.

What works is to divide the code up so that your context is fully initialized before you try to use it.

So take the following line of code and split it into two lines of code:

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

Dividing it up into two lines:

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

It's a small change, but everything compiles and runs correctly now.