Thanks @Obelix, was looking how to do this, and downloaded that book and now I can happily design my screen in the preview with fake core data :)
So you don't have to go digging in the book you can create a PreviewDataController
under the Preview Content
folder of your project...
class PreviewDataController {
private let container = NSPersistentContainer(name: "DiceRolls")
var viewContext: NSManagedObjectContext {
container.viewContext
}
init() {
container.persistentStoreDescriptions.first!.url = URL(fileURLWithPath: "/dev/null")
container.loadPersistentStores { description, error in
if let error = error {
print("Core Data failed to load: \(error.localizedDescription)")
}
}
}
func savePreviewData(diceRolls: [[String : Any]]) {
diceRolls.forEach { diceRollDict in
let diceRoll = DiceRoll(context: container.viewContext)
diceRoll.id = UUID()
diceRoll.totalRolled = diceRollDict["totalRolled"] as! Int16
diceRoll.numberOfSides = diceRollDict["numberOfSides"] as! Int16
diceRoll.numberOfDice = diceRollDict["numberOfDice"] as! Int16
diceRoll.dateOfRoll = diceRollDict["dateOfRoll"] as? Date
}
}
}
Then in your preview...
struct PreviousRollsView_Previews: PreviewProvider {
private static let diceRolls = [
[
"totalRolled": Int16(4),
"numberOfSides": Int16(6),
"numberOfDice": Int16(1),
"dateOfRoll": Date()
],
[
"totalRolled": Int16(12),
"numberOfSides": Int16(6),
"numberOfDice": Int16(2),
"dateOfRoll": Date()
],
[
"totalRolled": Int16(14),
"numberOfSides": Int16(4),
"numberOfDice": Int16(4),
"dateOfRoll": Date()
],
]
static var previews: some View {
let previewDataController = PreviewDataController()
previewDataController.savePreviewData(diceRolls: diceRolls)
return PreviousRollsView(isPresented: .constant(true))
.environment(
\.managedObjectContext,
previewDataController.viewContext
)
}
}