My App is crashing trying to insert into a ModelContext. Anything obvious that sticks out as to why?

  @Model
class MyDataClass {
    var number : String
    var pageNumberInDocument : Int
    
    init(number: String, pageNumberInDocument: Int) {
        self.number = number
      self.pageNumberInDocument = pageNumberInDocument
    }
}



@main
struct MyApp: App {
var body: some Scene {
        WindowGroup {
      ContentView()
     }.modelContainer(for:[MyDataClass.self])
 }
}


struct SaveMyData {
    @Environment(\.modelContext) var context
    
     func saveData(number: String, pageNumberInDocument : Int) {
    let dataToSave = MyDataClass(number: number, pageNumberInDocument: Int(pageNumberInDocument)!)
    
    context.insert(dataToSave)
    }
}

All seems pretty basic and correct to me. My crash ....

*** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: 'Cannot insert 'MyDataClass' in this managed object context because it is not found in the associated managed object model.'

I have seen the same issue on the Apple dev forums but no significant reply to that thread. Hence my post. Really appreciate anyone able to even just state the obvious to me. Thank SO

2

There are 2 best solutions below

2
On BEST ANSWER

You can't use @Environment outside of a View so you need to inject the model context instead. The easiest way to do this is to pass it to the function

func saveData(number: String, pageNumberInDocument: Int, context: ModelContext) {
    let dataToSave = MyDataClass(number: number, pageNumberInDocument: Int(pageNumberInDocument)!)

    context.insert(dataToSave)
}

Since the function isn't accessing self in any way you could make it static if you want.

1
On

The solution that worked for me was to move the .modelContext modifier to my ContentView() instead of being on the WindowGroup(). That’s what got rid of the error for me.