iosswiftswiftuicore-datauipickerview

SwiftUI - Using CoreData Fetched Result to Populate Picker


I'm following every guide I've seen online to bring in the managed object to the SwiftUI scene with environment and then run a @FetchRequest in the scene, all of it works great.

I can use that result to populate the value of a picker

Heres what I have

CoreData Object

    public class CD_LookupData: NSManagedObject,Identifiable {}


extension CD_LookupData {

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

    @NSManaged public var lookluptable: String?
    @NSManaged public var primarykeyid: String?
    @NSManaged public var value: String?

}

SwiftUI View

struct LabledSelectBoxCD: View {
    var label: String
    var lookupdata: FetchedResults<CD_LookupData>

    @Binding var value: Int

    var body: some View
    {
        VStack(alignment: .leading)
        {
            Picker(selection: $value, label: Text(""))
            {
                ForEach(lookupdata, id: \.primarykeyid)
                { data in
                    Text(data.value ?? "Unknown")
                }
            }
        }
    }
}

Its populates the picker with the values just fine but my default value never works and no value selected is saved.

If I try the same view with just an array of strings it works perfectly.

Any ideas on how I can get it to use the value of primarykeyid for the value of the picker?

Update:

@Binding var value: String

and

Text(data.value ?? "Unknown").tag(data.primarykeyid)

Don't make any changes


Solution

  • You need to make your value an optional String because that is what the type primaryKeyId is

    @Binding var value: String?
    

    And then you need a tag on each element of the picker to set the selection:

    Text(data.value ?? "Unknown").tag(data.primaryKeyId)