Files
workoutsplus/WorkoutsPlus/SampleData.swift
T
2024-08-22 14:55:59 +02:00

57 lines
1.6 KiB
Swift
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
//
// SampleData.swift
// WorkoutsPlus
//
// Created by Felix Förtsch on 17.08.24.
//
import Foundation
import SwiftData
@MainActor // With your annotation, youre 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, youve 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.")
}
}
}