UPGRADE YOUR SKILLS: Learn advanced Swift and SwiftUI on Hacking with Swift+! >>

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 {
        ContentView()
            .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"
        book.author = "Test author"
        book.genre = "Fantasy"
        book.rating = 4
        book.review = "This was a great book; I really enjoyed it."

        return NavigationView {
            DetailView(book: book)
        }
    }
}

3      

Hacking with Swift is sponsored by Essential Developer

SPONSORED Join a FREE crash course for mid/senior iOS devs who want to achieve an expert level of technical and practical skills – it’s the fast track to being a complete senior developer! Hurry up because it'll be available only until April 28th.

Click to save your free spot now

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

Archived topic

This topic has been closed due to inactivity, so you can't reply. Please create a new topic if you need to.

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.