在 SwiftUI Picker 中为 NSManagedObject 设置默认值?

Setting a default value for an NSManagedObject in SwiftUI Picker?

我正在 SwiftUI 中使用 Picker 从核心数据 NSManagedObject 列表中进行选择,但无法让选择器显示默认值。选择一个后,它也不会设置新值。有没有办法让选择器显示默认值?

这里是我的 NSManagedObject 属性设置的地方。

extension Company {

    @nonobjc public class func fetchRequest() -> NSFetchRequest<Company> {
        return NSFetchRequest<Company>(entityName: "Company")
    }

    @NSManaged public var id: UUID?
    @NSManaged public var name: String?
    @NSManaged public var companyContacts: NSSet?
    @NSManaged public var companyRoles: NSSet?

    //...

}

这是我尝试使用它的地方。

struct AddRoleSheet: View {
    @Environment(\.managedObjectContext) var moc
    @FetchRequest(
        entity: Company.entity(),
        sortDescriptors: [
            NSSortDescriptor(keyPath: \Company.name, ascending: true)
        ]
    ) var companies: FetchedResults<Company>

//...

@State var company: Company? = // Can I put something here? Would this solve my problem?

//...

var body: some View {
    NavigationView {
        Form {
            Section {
                Picker(selection: $company, label: Text("Company")) {
                    List {
                        ForEach(companies, id: \.self) { company in
                            company.name.map(Text.init)
                        }
                    }
                }
                //...
            }
        }
        //...
    }
}

View.init 阶段还没有获取结果,因此请尝试以下操作

@State var company: Company? = nil   // << just initialize

//...

var body: some View {
    NavigationView {
        Form {
            Section {
                Picker(selection: $company, label: Text("Company")) {
                    List {
                        ForEach(companies, id: \.self) { company in
                            company.name.map(Text.init)
                        }
                    }
                }
                //...
            }
        }
    }.onAppear {
       // here companies already fetched from database
       self.company = self.companies.first      // << assign any needed
    }
}