create a view model that will store data in swift data

Generated on 8/3/2024

1 search

To create a view model that will store data using SwiftData, you can follow the steps outlined in the WWDC sessions. Here’s a basic example to get you started:

  1. Define Your Model: Use the @Model macro to define your data model.

  2. Create a Model Container: Use the ModelContainer to manage your data.

  3. Create a View Model: Define a view model that interacts with the ModelContainer.

Here’s a simple implementation:

Step 1: Define Your Model

import SwiftData

@Model
class Trip {
    @Attribute(.unique) var id: UUID
    var destination: String
    var date: Date

    init(destination: String, date: Date) {
        self.id = UUID()
        self.destination = destination
        self.date = date
    }
}

Step 2: Create a Model Container

import SwiftData

struct TripsApp: App {
    var body: some Scene {
        WindowGroup {
            ContentView()
                .modelContainer(for: Trip.self)
        }
    }
}

Step 3: Create a View Model

import SwiftUI
import SwiftData

class TripsViewModel: ObservableObject {
    @Published var trips: [Trip] = []
    private var modelContext: ModelContext

    init(modelContext: ModelContext) {
        self.modelContext = modelContext
        fetchTrips()
    }

    func fetchTrips() {
        let request = Trip.fetchRequest()
        if let fetchedTrips = try? modelContext.fetch(request) {
            trips = fetchedTrips
        }
    }

    func addTrip(destination: String, date: Date) {
        let newTrip = Trip(destination: destination, date: date)
        modelContext.insert(newTrip)
        try? modelContext.save()
        fetchTrips()
    }
}

Step 4: Use the View Model in a SwiftUI View

import SwiftUI

struct ContentView: View {
    @StateObject private var viewModel: TripsViewModel

    init() {
        let modelContext = ModelContext(container: ModelContainer(for: Trip.self))
        _viewModel = StateObject(wrappedValue: TripsViewModel(modelContext: modelContext))
    }

    var body: some View {
        VStack {
            List(viewModel.trips) { trip in
                Text(trip.destination)
            }
            Button(action: {
                viewModel.addTrip(destination: "New York", date: Date())
            }) {
                Text("Add Trip")
            }
        }
    }
}

Relevant Sessions

These sessions provide a comprehensive overview of how to use SwiftData for data persistence and custom data stores.