57 lines
1.6 KiB
Swift
57 lines
1.6 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([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() {
|
||
// Erstellt ein Dictionary, um Übungen nach Namen nachzuschlagen
|
||
var exercisesDict = [String: Exercise]()
|
||
|
||
// Alle Übungen in der Datenbank speichern und im Dictionary ablegen
|
||
for exercise in Exercise.sampleData {
|
||
if exercisesDict[exercise.name] == nil {
|
||
context.insert(exercise)
|
||
exercisesDict[exercise.name] = exercise
|
||
}
|
||
}
|
||
|
||
// Workouts erstellen und dabei vorhandene Übungen referenzieren
|
||
for workout in Workout.sampleData(using: exercisesDict) {
|
||
context.insert(workout)
|
||
}
|
||
|
||
do {
|
||
try context.save()
|
||
} catch {
|
||
print("Sample data context failed to save.")
|
||
}
|
||
}
|
||
}
|