Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Mock Core Data object in SwiftUI Preview

Xcode’s preview canvas keeps on crashing with no error message when I try to pass in a preview Core Data object like so:

import SwiftUI
import CoreData

struct BookView: View {
    let book: Book
    
    var body: some View {
        Text("Hello, World!")
    }
}

// ^^^ This stuff is fine ^^^

// vvv This stuff is not vvv

struct BookView_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 {
            BookView(book: book)
        }
    }
}

I’m following a Hacking with Swift tutorial on Core Data and SwiftUI and am at this step.

This appears to be the standard way to add preview objects into the SwiftUI canvas, but I’m unable to get it to work. FYI the app runs fine in the simulator, I’m just trying to get it to also work in the preview canvas. I’m using Xcode 13.2.1 on macOS 12.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Thank you!

>Solution :

Instead of creating a NSManagedObjectContext use

static let context = PersistenceController.preview.container.viewContext

That variable is provided in the standard Xcode project with Core Data.

Also, if you have been using the real store for preview it might be corrupted somehow so you might have to destroy.

Add the code below

    do{
        try container.persistentStoreCoordinator.destroyPersistentStore(at: container.persistentStoreDescriptions.first!.url!, type: .sqlite, options: nil)
    }catch{
        print(error)
    }

Right under

container = NSPersistentCloudKitContainer(name: "YourAppName")

Before you load the store.

This destroys the store and then it gets recreated when you call loadPersistentStores be sure to remove that piece of code after you clear the preview device so you don’t accidentally destroy another store you don’t mean to destroy.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading