NEW: My new book Pro SwiftUI is out now – level up your SwiftUI skills today! >>

Day 56: Bookworm. Preview crashes when using moc - SOLVED

Forums > 100 Days of SwiftUI

When using moc in my previews I experienced crashes in preview (canvas). Everything worked on the simulator. The preview would just crash. Looking at the Diagnostics, this was the error reported:

Exception thrown while invoking -[PreviewsInjection.UVPreviewNonUIAgent performUpdate:replyHandler:]: An NSManagedObject of class 'Book' must have a valid NSEntityDescription

The solution proposed in the lesson Showing book details didn't work for me. Solutions to similar problems, like this one from this forum didn't fully resolve the issue either.

Putting the two together solved the issue for me. What I had to do on some preview structures is:

struct ContentView_Previews: PreviewProvider {

    static var dataController = DataController()

    static var previews: some View {
            .environment(\.managedObjectContext, dataController.container.viewContext)

struct DetailView_Previews: PreviewProvider {
    static var dataController = DataController()
    static var moc = dataController.container.viewContext

    static var previews: some View {
        let book = Book(context: moc)
        book.title = "Test book" = "Test author"
        book.genre = "Fantasy"
        book.rating = 4 = "This was a great book; I really enjoyed it."

        return NavigationView {
            DetailView(book: book)


Hacking with Swift is sponsored by Judo

SPONSORED Let’s face it, SwiftUI previews are limited, slow, and painful. Judo takes a different approach to building visually—think Interface Builder for SwiftUI. Build your interface in a completely visual canvas, then drag and drop into your Xcode project and wire up button clicks to custom code. Download the Mac App and start your free trial today!

Try now

Sponsor Hacking with Swift and reach the world's largest Swift community!

Reply to this topic…

You need to create an account or log in to reply.

All interactions here are governed by our code of conduct.

Unknown user

You are not logged in

Log in or create account

Link copied to your pasteboard.