當我嘗試像這樣傳遞預覽 Core Data 物件時,Xcode 的預覽畫布不斷崩潰,沒有錯誤訊息:
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)
}
}
}
我正在學習關于 Core Data 和 SwiftUI 的 Hacking with Swift 教程,并且正在這一步。
這似乎是將預覽物件添加到 SwiftUI 畫布的標準方法,但我無法讓它作業。僅供參考,該應用程式在模擬器中運行良好,我只是想讓它也能在預覽畫布中運行。我在 macOS 12 上使用 Xcode 13.2.1。
謝謝!
uj5u.com熱心網友回復:
而不是創造一個NSManagedObjectContext用途
static let context = PersistenceController.preview.container.viewContext
該變數在帶有 Core Data 的標準 Xcode 專案中提供。
此外,如果您一直在使用真實商店進行預覽,它可能會以某種方式損壞,因此您可能不得不銷毀。
添加下面的代碼
do{
try container.persistentStoreCoordinator.destroyPersistentStore(at: container.persistentStoreDescriptions.first!.url!, type: .sqlite, options: nil)
}catch{
print(error)
}
正下方
container = NSPersistentCloudKitContainer(name: "YourAppName")
在加載商店之前。
這會破壞商店,然后當您呼叫loadPersistentStores一定要在清除預覽設備后洗掉那段代碼時重新創建它,這樣您就不會意外地破壞另一個您不想破壞的商店。
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/393677.html
上一篇:從陣列中添加兩個整數
