Reputation: 107
I have a view that gets a core data instance as an argument:
let timerObject: TimerObject
var body: some View {
Text(timerObject.name)
}
But now of course my preview throws an error because of course it needs a value for my view:
struct TimerView_Previews: PreviewProvider {
static var previews: some View {
TimerView(timerObject: ???)
}
}
if it were simple values like a string that I have to pass in then of course I can use .constant(...). Only which test value can I pass here with a core data object? Can I perhaps pass a test instance from the persistence file or something like that?
I would be very happy to hear from you! Best regards
Upvotes: 3
Views: 1148
Reputation: 12125
Using the Xcode core data template, I did the following.
My model has create funcs for all objects. The principle is:
extension TimerObject {
static func create(
pos: Int = 0, // replace with your properties
title: String = "",
inContext ctx: NSManagedObjectContext
) -> Self {
let record = self.init(context: ctx)
record.id = UUID()
record.pos = Int16(pos) // replace with your properties
record.title = title
saveContext(context: ctx)
return record
}
}
Then you can use those in the previews:
struct TimerView_Previews: PreviewProvider {
static var previews: some View {
// this is the Xcode generated preview container
let ctx = PersistenceController.preview.container.viewContext
let timer = TimerObject.create(pos: 0, title: "Test", inContext: ctx)
TimerView(timerObject: timer)
.environment(\.managedObjectContext, ctx)
}
}
Upvotes: 5