0

I want to save my string array to core data I've tried this solution but I m using SwiftUI.

My entity has 3 variable (date(Date), name(String), values(Transformable)) problem is with values. When I write result.name! I can show data of course but I don t know the saving array of string what is the logic behind of this operation

ContentView

struct ContentView: View {
    
    @Environment(\.managedObjectContext) var context
    @FetchRequest(entity: Item.entity(), sortDescriptors: [NSSortDescriptor(key: "date", ascending: true)],animation: .spring()) var results : FetchedResults<Item>

    
    @State var name = ""
    @State var value1 = ""
    @State var value2 = ""
    @State var myArray = [String]()

    var body: some View {
        
        
        VStack {
            
            Form{
                
                Section(header: Text("Test")) {
                    
                    TextField("Input", text: $name)
                    TextField("Value 1", text: $value1)
                    TextField("Value 2", text: $value2)
                    
                }
                
                Button(action: {
                    
                    self.myArray.append(value1)
                    self.myArray.append(value2)
                    saveData(context: context)
                    
                }, label: {
                    
                    Text("Next")
                })
            }
        }
        
        ForEach(results){result in
            
            Text("Result:" + result.values) this line has an error -> (Value of type 'NSManagedObject' has no member 'values')
        }
        
    }
    
    func saveData(context: NSManagedObjectContext){
        
        let task = Item(context: context)
        task.name = name
        task.values = self.myArray as NSObject
        
        do {
            try context.save()
        } catch {
            
            print("error")
        }
    }
}
Witek Bobrowski
  • 3,749
  • 1
  • 20
  • 34
jrIosDev
  • 37
  • 1
  • 7

1 Answers1

0

Make sure that you have told CoreData to expect a [String] for your Transformable per your reference.

enter image description here

Then change the Text in your ForEach to

Text("Result:" + (result as Item).values!.count.description)

Then in your saveData() remove NSObject

task.values = self.myArray
lorem ipsum
  • 21,175
  • 5
  • 24
  • 48