I have an app Im trying to build with sleep data for sleep apnea. I successfully setup CoreData with some help and its saving the first user input from the textfields and displaying it in the log from CoreData (changing the strings to Doubles was a challenge but success). However, whenever I put another 2nd input in, it saves and displays the first input again. It won't change. What am I doing wrong? A side note, it also is not creating a unique ID for each entry for some reason. Thank you guys....you'd been awesome so far helping as Im a newbie.
SleepModel.swift
struct SleepModel: Identifiable, Hashable {
var id = UUID().uuidString // ID variable
var hoursSlept: Double // Hours slept variable
var ahiReading: Double // AHI variable
}
Save function in AddEntryView.swift which is called when the button is pushed
private func saveSleepModel() {
guard let hoursSleptDouble = Double(hoursSleptString) else {
print("hours slept is invalid")
return
}
guard let ahiReadingDouble = Double(ahiReadingString) else {
print("ahi reading is invalid")
return
}
// Creates Sleep Model for user input & sends parameters
var sleepModel = SleepModel(hoursSlept: hoursSleptDouble, ahiReading: ahiReadingDouble)
coreDataViewModel.saveRecord(sleepModel: sleepModel) {
print("Success")
}
}
CoreDataViewModel
import SwiftUI
import CoreData
class CoreDataViewModel: ObservableObject {
let container: NSPersistentContainer
@Published var savedRecords: [SleepEntity] = []
init() {
container = NSPersistentContainer(name: "SleepContainer")
container.loadPersistentStores { description, error in
if let error = error {
print("Error loading contaienr - \(error.localizedDescription)")
} else {
print("Core data loaded successfully")
}
}
fetchRecords()
}
func saveRecord(sleepModel: SleepModel, onSuccess: @escaping() -> Void) {
let newRecord = SleepEntity(context: container.viewContext)
newRecord.hoursSlept = sleepModel.hoursSlept
newRecord.ahiReading = sleepModel.ahiReading
saveData(onSuccess: onSuccess)
}
func saveData(onSuccess: @escaping() -> Void) {
do {
try container.viewContext.save()
fetchRecords()
onSuccess()
} catch let error {
print("Error saving items: \(error)")
}
}
func fetchRecords() {
let request = NSFetchRequest<SleepEntity>(entityName: "SleepEntity")
request.sortDescriptors = [
NSSortDescriptor(keyPath: \SleepEntity.id, ascending: false)
]
do {
savedRecords = try container.viewContext.fetch(request)
} catch let error {
print("Error fetching requests - \(error.localizedDescription)")
}
}
}