简体   繁体   中英

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.

Thank you!

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM