Question: How to reset Xcode's Preview Canvas? Specifically, how to erase all the Core Data in Canvas created in Canvas' Live Preview?
Example code: This is SwiftUI preview code I am using for Canvas preview.
struct ItemView_Previews: PreviewProvider {
static var previews: some View {
let context = (UIApplication.shared.delegate as! AppDelegate).persistentContainer.viewContext
//Test data
let testItem = Item.init(context: context)
testItem.name = "Abc"
return ItemView(filter: false)
.environment(\.managedObjectContext, context)
}
}
With this code Canvas shows me testItem, but also item.name of Core Data objects created in Live Preview. I would like to erase Canvas data to not see previously created objects.
Things I have tried: Xcode - Product > Clean Build Folder Xcode - Editor > Canvas > Refresh Canvas Simulator - Device > Erase All Content And Settings...
The last one works as expected for Simulator. I was hoping maybe it will erase Canvas data as well, but it doesn't.
--
Full working example:
ContentView.swift
import SwiftUI
import CoreData
struct ContentView: View {
@Environment(\.managedObjectContext) var managedObjectContext
@State var paidFilter :Bool? = nil
var body: some View {
NavigationView {
List {
ItemView(filter: paidFilter)
}
.listStyle(PlainListStyle())
.navigationTitle(Text("Items"))
.navigationBarItems(
trailing:
Button(action: {
let item = Item(context: self.managedObjectContext)
item.name = "Test"
do {
try self.managedObjectContext.save()
}catch{
print(error)
}
}) {
Image(systemName: "plus.circle.fill")
.font(.title)
}
)
}
.navigationViewStyle(StackNavigationViewStyle())
}
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
let context = (UIApplication.shared.delegate as! AppDelegate).persistentContainer.viewContext
return ContentView()
.environment(\.managedObjectContext, context)
}
}
ItemView.swift
import SwiftUI
struct ItemView: View {
@Environment(\.managedObjectContext) var managedObjectContext
var fetchRequest: FetchRequest<Item>
var items: FetchedResults<Item> { fetchRequest.wrappedValue }
init(filter: Bool?) {
fetchRequest = FetchRequest<Item>(entity: Item.entity(), sortDescriptors: [])
}
var body: some View {
VStack {
ForEach(items, id: \.self) {item in
Text("\(item.name ?? "test123")")
}
}
}
}
struct ItemView_Previews: PreviewProvider {
static var previews: some View {
let context = (UIApplication.shared.delegate as! AppDelegate).persistentContainer.viewContext
//Test data
let testItem = Item.init(context: context)
testItem.name = "Abc"
return ItemView(filter: false)
.environment(\.managedObjectContext, context)
}
}
addPersistentStoreWithType:NSInMemoryStoreType
) developer.apple.com/library/archive/documentation/Cocoa/… – Molybdenous