SwiftData multiple loop entries not inserting

For an array only the last row is inserted where print shows the loop is processed for index in 0..<model.dataTable!.rows.count {

                        let row = model.dataTable!.rows[index]
                        catagory.name = row["Catagory"] as! String
                        context.insert(catagory)
                        
                        print(catagory.name)
                    }

tried a forced try?save() which didn't help Thanks Joel

Answered by joadan in 801300022

You have a single Category object that you update inside the loop instead of creating a new category for each iteration.

Remove the category property and change your loop to something like this

for index in 0..<model.dataTable!.rows.count {
    let row = model.dataTable!.rows[index]
    let name = row["Catagory"] as! String
    let category = Category(id: UUID(), name: name, instrumen: [[)
    context.insert(catagory)
                        
    print(catagory.name)
}
    

Please provide enough information so we can understand and help.

  • show more code so that we can test and help ?
  • How is context defined ?
  • How and where is category defined ?

import Foundation import SwiftData import TabularData

@Model class Catagory {

var id: UUID
@Attribute(.unique)var name: String
var instrument: [Instrument] = [Instrument]()

init(id: UUID, name: String, instrument: [Instrument]) {
    self.id = id
    self.name = name
    self.instrument = instrument
}

} @Environment(.modelContext) private var context @Environment(.dismiss) private var dismiss

var catagory: Catagory
var model = DataModel.shared
@State private var overWrite: Bool = true
@State private var name: String = ""

Button("Save") { if overWrite { deleteModel(modelContext: context) } for index in 0..<model.dataTable!.rows.count {

                        let row = model.dataTable!.rows[index]
                        catagory.name = row["Catagory"] as! String
                        context.insert(catagory)
                        
                        print(catagory.name)
                    }
                   
                    dismiss()
                }
                .buttonStyle(.borderedProminent)
                .tint(.green)

func deleteModel(modelContext: ModelContext) { do { try modelContext.delete(model: Catagory.self) } catch { fatalError(error.localizedDescription) } }

Accepted Answer

You have a single Category object that you update inside the loop instead of creating a new category for each iteration.

Remove the category property and change your loop to something like this

for index in 0..<model.dataTable!.rows.count {
    let row = model.dataTable!.rows[index]
    let name = row["Catagory"] as! String
    let category = Category(id: UUID(), name: name, instrumen: [[)
    context.insert(catagory)
                        
    print(catagory.name)
}
    
SwiftData multiple loop entries not inserting
 
 
Q