Data Persistence not functioning upon refresh

Hello, I am attempting to implement a simple button that loads persistent data from a class (see below).

Button("Reload Data") {
      while tableData2.isEmpty == false{
          tableData2.remove(at: 0)
      }
      while tableView.isEmpty == false{
          tableView.remove(at: 0)
      }
      //update
      if csvData.isEmpty == false{
        for superRow in csvData[0].tableData2{
            tableData2.append(superRow)
        }
        for supperRow in csvData[0].tableView{
            tableView.append(supperRow)
        }
                            
        print("Item at 0: \(csvData[0].tableData2[[0][0]])")
        print("\(tableData2[0][0])")
      } else {
        print("csvData is empty")
      }

}

This button DOES work to appropriately print the data stored at the printed location once loaded in initially. The problem is that it doesn’t work across app restarts, which is the whole point of the button. Below I will include the rest of the relevant code with notes:

In contentView declaring the persistant variables:

Query private var csvData: [csvDataPersist]
Environment(\.modelContext) private var modelContext

The simple class of data I’m storing/pulling to/from:

@Model
class csvDataPersist{
    var tableView: [[String]] = []
    var tableData2: [[String]] = []
    
    init(tableView: [[String]], tableData2: [[String]]) {
        self.tableView = tableView
        self.tableData2 = tableData2
    }
}

In (appname)App: I tried both locations of the model container but it didn’t seem to matter

var body: some Scene {
        WindowGroup {
            ContentView()
                .modelContainer(for: csvDataPersist.self)
        }
        //.modelContainer(for: csvDataPersist.self)
        .modelContainer(sharedModelContainer)
    }

How I’m attempting to save the data:

let newCSVDataPersist = csvDataPersist(tableView: tableView, tableData2: tableData2)
                            
//modelContext.rollback()
                            
//for superrow in csvData.count{
//  csvData[superrow].tableData2.removeAll()
//}
//modelContext.rollback()
//csvData[0].tableData2.removeAll()
//csvData[0].tableView.removeAll()                            
                            
if csvData.isEmpty == false {
    print("not empty, deleting prev data")
    modelContext.delete(csvData[0])
} else {
    print("it empty, load data.")
}
modelContext.insert(newCSVDataPersist)
//try modelContext.save()

Note that I’ve tried just about every combination of enabling and disabling the commented out lines. This is the part of the code I am the least confident in, but after trying for hours to troubleshoot on my own I would appreciate any input from the community.

Something else that may be of note, in a previous attempt, upon a second startup, the terminal would print:

"coredata: error: error: persistent history (random number) has to be truncated due to the following entities being removed: ( csvdatapersist )"

Why is csvDataPersist getting removed? What is it getting removed by? Looking up this error was fruitless. Most sites instructed me to basically hard reset my simulators, clean the build, restart my computer, and try again. I've done all of these things about a hundred times at this point, with no results.

Any help would be much appreciated!

Unrelated perhaps but why are you even using SwiftData for this, wouldn't it be better to use a CSV (or JSON) file for persisting your data?

Maybe I am misreading the code but to me it looks like you only want to store a single instance of your model and then I believe SwiftData or any other database solution is overkill and that a simple file is more suitable.

The error message most likely happened because you changed the class name so the current SwiftData schema was different from what the existing store had used, as discussed here. I don't think that is the root cause of your issue.

What catches my eyes is that you commented out the modelContext.save(). SwiftData supports auto-save, and yet, auto-save happens periodically. If you stop running your app before auto-save happens, the data will not be persisted.

Other than that, I don't see any obvious issue in your code snippets. If you can share a runnable code that reproduces the issue, I may take another look.

Best,
——
Ziqiao Chen
 Worldwide Developer Relations.

Data Persistence not functioning upon refresh
 
 
Q