Hi there, I just started coding my first app in SwiftUI
I am recreating the date planner app, an app on Swift Playgrounds, and I can’t seem to make the data persists in a view programmatically.
I have created an observable class that contains a published property of type [Event] to store a Events in an array with functions that can add & remove events from it.
class EventData: ObservableObject {
@Published var events: [Event] = [
Event(symbol: "gift.fill",
color: .red,
name: "Kiko's Birthday",
tasks: [EventTasks(text: "Guava kombucha"),
EventTasks(text: "Paper cups and plates"),
EventTasks(text: "Cheese plate"),
EventTasks(text: "Party poppers"),
],
date: Date.roundedHoursFromNow(60 * 60 * 24 * 30)),
Event(symbol: "theatermasks.fill",
color: .yellow,
name: "mo’s promotion”
tasks: [EventTasks(text: "Buy new tux"),
EventTasks(text: "Get tickets"),
EventTasks(text: "Pick up Carmen at the airport and bring her to the show"),] ,
date: Date.roundedHoursFromNow(60 * 60 * 22)) ]
func delete(_ event: Event) {
events.removeAll { $0.id == event.id }
}
func add(_ event: Event) {
events.append(event)
}
}
I then created an instance of the class in the app root wrapped by the @stateobject property and passed it into the environment so the data becomes accessible to all views.
import SwiftUI
@main
struct MyApp: App {
@StateObject private var eventData = EventData()
var body: some Scene {
WindowGroup{
NavigationView{
EventList()
.foregroundColor(.green)
}
.environmentObject(eventData)
}
}
}
I then created a list that constructs the main view for the app from the array stored in Event Data class. I also created an editor in a modal sheet that allows users to add a new event, once triggered it automatically creates a new event and shows it into the list.
The problem is when the app reloads this data disappears as if it’s not stored in the array. And the only data that persists is the events that I added manually in the array.