簡體   English   中英

在 SwiftUI 中保存和檢索可轉換數據

[英]Save and retrieve transformable data in SwiftUI

我想將我的字符串數組保存到核心數據我已經嘗試過這個解決方案,但我使用的是 SwiftUI。

我的實體有 3 個變量(日期(日期)、名稱(字符串)、值(可轉換)),問題在於值。 當我寫result.name! 我當然可以顯示數據但我不知道字符串的保存數組這個操作背后的邏輯是什么

內容視圖

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")
        }
    }
}

確保您已告訴 CoreData 根據您的引用為您的Transformable期待一個[String]

在此處輸入圖像描述

然后將ForEach中的Text更改為

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

然后在你的saveData()中刪除NSObject

task.values = self.myArray

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM