Has anyone figured out how to generate sample data for a Preview Container that contains relationships? I've tried numerous ways to get a relationship, but have not had any success. I've searched around the forms and the internet to see if I can find anything, but haven't had any luck.
Here is what I have defined for my previewContainter
and the sample data structure. I've followed the same pattern that is found in WWDC2023 Build an app with SwiftData.
The books and tags are created just fine in memory, and in my SwiftUI previews, I can see these items.
Here is what I currently have, but I have also tried running a query after SampleData.books.forEach(container.mainContext.insert(object: ))
and then using one of the returned items for the relationship, but every query I perform in here returns an empty result.
Am I barking up the wrong tree with my approach, or is this a known issue that I have not come across?
@MainActor
let previewContainer: ModelContainer = {
do {
let container = try ModelContainer(
for: [Project.self, Recipe.self, Tag.self],
ModelConfiguration(inMemory: true)
)
// Add in sample data
SampleData.books.forEach(container.mainContext.insert(object: ))
SampleData.tags.forEach(container.mainContext.insert(object: ))
SampleData.recipes.forEach(container.mainContext.insert(object: ))
return container
} catch {
fatalError("Failed to create preview container")
}
}()
struct SampleData {
static let books: [Book] = {
return (1...5).map({ Book(title: "Sample Book #\($0)") })
}()
static let tags: [Tag] = {
return (1...5).map({ Tag(name: "Sample Tag #\($0)") })
}()
static let recipes: [Recipe] = {
(1...5).map({ Recipe(name: "Sample Recipe #\($0)", book: Self.books.first!) })
}()
}
Thanks