I need some help with SwiftData. I want to have a few instances of one of my SwiftData classes created only the first time the app opens. These instances should be created once when the app opens for the first time, and not on subsequent launches. I’ve tried hard-coding them, but SwiftData is giving me issues with this approach. It seems like SwiftData requires instances to be created by the app itself, rather than being hard-coded. Is there a proper way to initialize these instances only on the first app launch?
I’m a beginner and would appreciate any help. Thank you!
That is the example for the Swift-Data-Class:
@Model
class TexEmoji {
let id: UUID
var text: String
var emoji: String
init(text: String, emoji: String) {
self.id = UUID()
self.text = text
self.emoji = emoji
}
}
That is the code I tried for the @main App
@main
struct PersonalAdviceApp: App {
@Environment(.modelContext) private var context
func checkFirstLaunch() {
let hasLaunchedBefore = UserDefaults.standard.bool(forKey: "hasLaunchedBefore")
if !hasLaunchedBefore {
let instance1: TexEmoji = TexEmoji(text: "Standard-Text 1", emoji: "????")
context.insert(instance1)
let instance2: TexEmoji = TexEmoji(text: "Home-Page", emoji: "????")
context.insert(instance2)
UserDefaults.standard.set(true, forKey: "hasLaunchedBefore")
}
}
var body: some Scene {
WindowGroup {
TestPage()
.modelContainer(for: [Ergebnis.self, Seite.self, TexEmoji.self])
.onAppear {checkFirstLaunch()}
}
}
}
Unfortunately I always get the following Error:
*** Terminating app due to uncaught exception ‘NSInvalidArgumentException’, reason: ‘Cannot insert ‘TexEmoji’ in this managed object context because it is not found in the associated managed object model.’