WWDC22 SALE: Save 50% on all my Swift books and bundles! >>

Day55 – Making Previews work for DetailView

Forums > 100 Days of SwiftUI

The following code doesn't work. The diagnostics says something like: "An NSManagedObject of class 'Book' must have a valid NSEntityDescription."

struct DetailView_Previews: PreviewProvider {
    static let moc = NSManagedObjectContext(concurrencyType: .mainQueueConcurrencyType)

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

Does somebody have a solution?

   

Hello ! I have the same problem, does anyone have a solution ?

   

Same here... I am using Xcode 13.4, built for iOS 15.5, tried simulating on iPod touch (7th generation), iPhone 12, iPad (9th generation).

   

I was able to fix the issue by adding a Persistence.swift file following the example code here: https://www.hackingwithswift.com/forums/100-days-of-swiftui/day-54-bookworm-an-nsmanagedobject-of-class-book-must-have-a-valid-nsentitydescription/5043

I really like the solution from the video however which is just to delete all the preview code from DetailView.swift.

   

The general question here is:

How do I show mock core data objects in a SwiftUI preview provider?

I have another suggestion.

Check out Mark Moeykens' excellent eBook titled, Core Data Quick Start in SwiftUI dated, 22 June 2022.

Our own @twoStraws is mentioned in the opening credits.

Mark writes nearly nine pages with plenty of notes and graphics explaining how to populate a temporary CoreData datastore with sample objects so that you can view fake CoreData records in your previews. Sweet!

The book is excellent and is free.

See -> Mark's Excellent Core Data Book

   

Hacking with Swift is sponsored by Fernando Olivares

SPONSORED Fernando's book will guide you in fixing bugs in three real, open-source, downloadable apps from the App Store. Learn applied programming fundamentals by refactoring real code from published apps. Hacking with Swift readers get a $10 discount!

Read the book

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.