Search code examples
iosswiftuipickerview

Setting Picker to default to CoreData value?


I have 2 pickers, the user sets their desired int on them and then saves the object to core data.

Later when they want to edit the object they reload its data into the editor.

I am having an issue where the pickers cannot pull the int back from core data and default themselves to this value, they always default to '0'

Is there a method to make the pickers default to the desired int stored in the object they are editing?

I have the following delegate methods in place:

    repsPicker.dataSource = self
    repsPicker.delegate = self
    setsPicker.dataSource = self
    setsPicker.delegate = self

I then try to take the properties from the object and apply them to the pickers, however im using NUMBER? in place of where id assume i need ot put code to access the default values of the pickers, here is where im stuck...

 setsPicker.selectedRow(inComponent: Int(userExercise.sets))
 repsPicker.selectedRow(inComponent: Int(userExercise.reps))

The data type of userExercise.sets or .reps is Int64 if that helps?

Many thanks for your time and assistance

edit-

here is the component override

func numberOfComponents(in pickerView: UIPickerView) -> Int {
    if pickerView == repsPicker {
        return 1
    } else if pickerView == setsPicker {
        return 1
    }
    return 1
}

Solution

  • you should use selectRow func not selectedRow

    func selectRow(_ row: Int,
       inComponent component: Int,
          animated animated: Bool)
    

    so, it should be

    setsPicker.selectRow(Int(userExercise.sets), inComponent :0,animated:false)
    repsPicker.selectRow(Int(userExercise.reps), inComponent :0,animated:false)