SwiftUI 试图从 FetchedResults 获取对象但没有找到方法

Posted

技术标签:

【中文标题】SwiftUI 试图从 FetchedResults 获取对象但没有找到方法【英文标题】:SwiftUI Trying to get object from FetchedResults but not finding a way 【发布时间】:2020-05-07 15:17:11 【问题描述】:

我有一个 FetchedResults 列表,我正在通过 Picker 从该 FetchedResults 中挑选一个对象,但不知道如何存储该对象。我正在通过变量 listOfPolymers 中的 FetchedRequest 从 CoreData 实体中获取对象列表。现在我想拾取一个对象作为父家庭,但我无法找到一种方法来从 Picker 中拾取所选对象。如果我在 Picker 中使用对象类型,则会出现错误,因为绑定对象需要从我要从该视图传递到该视图的视图传递,但我没有提供从该视图传递该对象的规定。这是我的代码:

struct Polymer: View 
@Environment(\.managedObjectContext) var mocPolymer
@FetchRequest(entity: AECPolymer.entity(), sortDescriptors: [NSSortDescriptor(keyPath: \AECPolymer.name, ascending: true)]) var listOfPolymers: FetchedResults<AECPolymer>
@State var toAddPolymerName: String = ""
@State var toAddPolymerShortName: String = ""
@State var addPolymer: Bool = false
@State var parentPolymerName: String = "Select"
@State var hasParent: Bool = false

var body: some View 
    List 
        if addPolymer 
            Section(header: Text("Add Polymer")) 
                TextField("Name", text: $toAddPolymerName)
                TextField("Short Name", text: $toAddPolymerShortName)
                Toggle(isOn: $hasParent) 
                    Text("Belongs to a Parent Polymer Family?")
                
                VStack 
                    if hasParent 
                        Picker(selection: $parentPolymerName, label: EmptyView()) 
                        ForEach(listOfPolymers, id: \.self) (parent: AECPolymer) in
                            Text(parent.name ?? "Unknown")
                        
                        
                     else 
                        EmptyView()
                    
                
                if self.toAddPolymerName.isEmpty || self.toAddPolymerShortName.isEmpty 
                    EmptyView()
                 else 
                    Button(action: 
                        let toAddPolymer = AECPolymer(context: self.mocPolymer)
                        toAddPolymer.name = self.toAddPolymerName
                        toAddPolymer.shortName = self.toAddPolymerShortName
                        let selectedParentPolymerName = self.parentPolymerName
                        if let parentPolymer = self.listOfPolymers.first(where:  "name == @%", selectedParentPolymerName ) 
                            toAddPolymer.polymerFamily = parentPolymer
                        

                        do 
                            try self.mocPolymer.save()
                         catch 
                            let nserror = error as NSError
                            fatalError("Unresolved error \(nserror), \(nserror.userInfo)")
                        
                        self.toAddPolymerName = ""
                        self.toAddPolymerShortName = ""
                        self.addPolymer.toggle()
                    , label: 
                        Text("Save")
                    ).buttonStyle(BorderlessButtonStyle())
                
            
         else 
            EmptyView()
        
        Section(header: Text("Polymers")) 
            if self.listOfPolymers.count != 0 
                ForEach(listOfPolymers, id: \.self) (polymer: AECPolymer) in
                    VStack(alignment: .leading) 
                        Text(polymer.name ?? "Unknown")
                        Text("(\(polymer.shortName ?? "Unknown"))").font(.footnote)
                    
                
             else 
                Text("List is empty...")
            
        
    .navigationBarTitle("List")
        .navigationBarItems(trailing: Button(action: 
            self.addPolymer.toggle()
        , label: 
            if self.addPolymer 
                Text("Cancel")
             else 
                Image(systemName: "plus.circle.fill")
                    .imageScale(.large)
            
        ))

有人可以帮助我如何获取用户从选择器中选择的对象...

【问题讨论】:

【参考方案1】:

CoreData 问题有点困难,因为很难让它们在本地编译。不过,试试这个:(不编译,只是给你一个方向!)

struct PickerView: View 
  @State private var selection: Int? = nil     // Int? state 
  var body: some View 
    Picker(selection: $selection, label: EmptyView()) 
      ForEach(YourModel.indices)  index in    // Loop over your model's Int index  
        Text("\(YourModel.name)").tag(index).  // Tag the text with the index
       
     
  

用户做出选择后,您应该通过索引找到您的对象:YourModel[$selection!]。当然,请确保提防nil 或提供默认值。

【讨论】:

以上是关于SwiftUI 试图从 FetchedResults 获取对象但没有找到方法的主要内容,如果未能解决你的问题,请参考以下文章

SwiftUI 试图从列表中删除对象但无法在不可变值上使用变异成员:是一个“让”常量

从 SwiftUI 中的列表中删除绑定

从结构数据 SwiftUI 创建一个数组

无法将数据从 Firebase 附加到数组 SwiftUI

SwiftUI - 试图在 ScrollView 中保持 View 的全屏大小

macOS 上的 SwiftUI:如何为 onDelete 启用 UI(从列表中删除)