51 lines
1.3 KiB
Swift
51 lines
1.3 KiB
Swift
//
|
||
// SampleData.swift
|
||
// WorkoutsPlus
|
||
//
|
||
// Created by Felix Förtsch on 17.08.24.
|
||
//
|
||
|
||
import Foundation
|
||
import SwiftData
|
||
|
||
@MainActor // With your annotation, you’re declaring that all code in this class must run on the main actor, including access to the mainContext property. Since all the SwiftUI code in an app runs on the main actor by default, you’ve satisfied the condition.
|
||
class SampleData {
|
||
static let shared = SampleData()
|
||
|
||
let modelContainer: ModelContainer
|
||
|
||
var context: ModelContext {
|
||
modelContainer.mainContext
|
||
}
|
||
|
||
private init() {
|
||
let schema = Schema([WorkoutItem.self, Exercise.self, Workout.self])
|
||
let modelConfiguration = ModelConfiguration(schema: schema, isStoredInMemoryOnly: true)
|
||
|
||
do {
|
||
modelContainer = try ModelContainer(for: schema, configurations: [modelConfiguration])
|
||
insertSampleData()
|
||
} catch {
|
||
fatalError("Could not create ModelContainer: \(error)")
|
||
}
|
||
}
|
||
|
||
func insertSampleData() {
|
||
for exercise in Exercise.sampleData {
|
||
context.insert(exercise)
|
||
}
|
||
|
||
for workoutItem in WorkoutItem.sampleData {
|
||
context.insert(workoutItem)
|
||
}
|
||
|
||
context.insert(Workout.sampleData)
|
||
|
||
do {
|
||
try context.save()
|
||
} catch {
|
||
print("Sample data context failed to save.")
|
||
}
|
||
}
|
||
}
|