Search code examples
swiftcore-dataswiftuipreview

SwiftUI Preview crashes with Core Data 'NSInvalidArgumentException'


I have the problem that I can't preview the View of my app with Canvas, because I always get the error:

"Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: 'An NSManagedObject of class 'App.MPG_A' must have a valid NSEntityDescription."

Now more detailed: In the view I want to preview I have a @Binding of the abstract class MultiplayerGame (MPG A or MPG B (subclasses) and the MultiplayerGame is a subclass of Game (picture below)

App Model

Comment: MultiplayerGame is also an abstract entity (like Game) and "Class" -> "MPG B"

And when I want to preview the class the following class by making a moc Object in the Preview my App crashes but I don't know why:

    import SwiftUI
import CoreData
import Combine

struct StandingEditView: View {
    
    //multiplayer game with MPG A or MPG B class
    @Binding var game : MultiplayerGame
    
    @State private var invokeFunction : Bool = false
    
    var body: some View {
        
        VStack{
            
            List{
                
                ForEach(game.players!, id: \.self){ player in
                    
                    HStack{
                        Text("\(player.name)")
                    }
                    
                }
                
            }
            
            Button(action: {
                invokeFunction.toggle()
            }, label: {
                Text("Button")
            })
            
        }
        
    }
}

struct StandingEditView_Previews: PreviewProvider {
    
    static let moc = NSManagedObjectContext(concurrencyType: .mainQueueConcurrencyType)
    
    static var previews: some View {
        
        let game : MultiplayerGame = Standing(context: moc)
        
        let p1 : Player = Player(context: moc)
        let p2 : Player = Player(context: moc)
        let p3 : Player = Player(context: moc)
        
        p1.name =  "Player One"
        p2.name =  "Player Two"
        p3.name =  "Player Three"
        
        game.players = [p1,p2,p3]
        
        return StandingEditView(game: .constant(game))
    }
}

And the only (not default) attributes of Player is -> var name : String

I also tried with AppDelegate but that didn't work either...

The error must occur because of the Preview and moc-Object because the Code itself compiles and the other Views are visible without an error.

Thank you for your help!


Solution

  • Since I have tried all other possibilities and nothing has helped, I have created a new project and checked CoreData.

    Then I created the main class in the CoreData file and replaced Item with Game in "ContentView".

    Also in the PersistenceController I replaced the Item with Game under the var preview : PersistenceController and created all classes with codegen "Manual/None".

    Now everything works.