Oleksandr Matrosov
Oleksandr Matrosov

Reputation: 27187

SwiftUI ForEach with UUID vs NSManagedObjectID in Core Data

I use MVVM as a pattern for my SwiftUI project.

I have simple model:

struct Medication: Identifiable {
    let id: UUID
    let name: String
    let dosage: String
    let time: Date
}

to display a list of medications I use this code:

var body: some View {
    NavigationView {
        VStack {
            List {
                ForEach(viewModel.medications) { med in... skipping display details

as we know we need let id: UUID for enumeration here ForEach(viewModel.medications).

This is how I add medication:

private func addMedication() {
        let newMedication = Medication(id: UUID(), name: name, dosage: dosage, time: time)
        viewModel.addMedication(newMedication)
        presentationMode.wrappedValue.dismiss()
    }

The problem is that initializer wants me to pass id: UUID() when creating Medication struct. But I actually need to save this medication data to Core Data which uses the unique NSManagedObjectId meaning I don't need UUID in sqlite records.

Potential risk if we store UUID in Core Data and work with this property using Medication struct is duplicating id but NSManagedObjectId only GET property and we can compromise it.

The question is how to actually make it logically correct as we have two types of id: UUID and NSManagedObjectId

To give you more context so I have a manager which save this Medication data to Core Data storage:

func saveMedication(_ medication: Medication, completion: @escaping (Bool) -> Void) {
        let medicationEntity = MedicationEntity(context: context)
        medicationEntity.name = medication.name
        medicationEntity.dosage = medication.dosage
        medicationEntity.time = medication.time

        do {
            try context.save()
            print("✅ Medication saved successfully!")
            completion(true)
        } catch {
            print("❌ Failed to save medication: \(error.localizedDescription)")
            completion(false)
        }
    }

For sure I can extend Medication struct like this:

struct Medication: Identifiable {
        let id: UUID
        let objectId: NSManagedObjectID // or String type
        let name: String
        let dosage: String
        let time: Date
    }

Or even store NSManagedObejct, but I want to make model for my MVVM as simple as I can, but the problem of two identifiers is adding a mess to my ideal world.

I mean I like version just with one id but I guess it's not save to use UUID instead of NSManagedObjectId to work with records, let's say I will need to update or remove medication from the list I need to know at least identifier or store NSManagedObject which overload my simple model layer.

Upvotes: -2

Views: 85

Answers (0)

Related Questions