简体   繁体   English

在 SwiftUI 中保存和检索可转换数据

[英]Save and retrieve transformable data in SwiftUI

I want to save my string array to core data I've tried this solution but I m using SwiftUI.我想将我的字符串数组保存到核心数据我已经尝试过这个解决方案,但我使用的是 SwiftUI。

My entity has 3 variable (date(Date), name(String), values(Transformable)) problem is with values.我的实体有 3 个变量(日期(日期)、名称(字符串)、值(可转换)),问题在于值。 When I write result.name!当我写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")
        }
    }
}

Make sure that you have told CoreData to expect a [String] for your Transformable per your reference.确保您已告诉 CoreData 根据您的引用为您的Transformable期待一个[String]

在此处输入图像描述

Then change the Text in your ForEach to然后将ForEach中的Text更改为

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

Then in your saveData() remove NSObject然后在你的saveData()中删除NSObject

task.values = self.myArray

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM