Save UIPickerView selection to NSUserDefaults swift

1k views Asked by At

I am trying to save the user's selection from UIPickerView to NSUserDefaults. I have found answers in obj-c but not swift. Here is my UIPickerView code:

func numberOfComponentsInPickerView(pickerView: UIPickerView) -> Int {
        return 1
    }
    func pickerView(pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
        return pickerData.count
    }
    func pickerView(pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String! {
        return pickerData[row]
    }

    func pickerView(pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {
        race = pickerData[row]
    }

And when you press a save button, it is supposed to save what is selected to NSUserDefaults. Here is my saving code:

@IBAction func save(sender: AnyObject) {
        var defaults: NSUserDefaults = NSUserDefaults.standardUserDefaults()
        defaults.setObject(race, forKey: "race")
    }

When I try to display the text on a label, it shows up blank:

override func viewDidLoad() {
        super.viewDidLoad()

        self.raceLabel.text = defaults.objectForKey("race") as? String

Let me know if my question needs any clarification, thanks.

1

There are 1 answers

0
bibscy On

Update your code as specified below and it will work

func pickerView(pickerView: UIPickerView, didSelectRow row: Int, inComponent     component: Int) {
    race = row   
}

Every time you select a row, this function is called and the argument of the parameter row represents the row that was selected in your UIPickerView.

If you assign pickerData[row] value to race, you are assigning a value from your pickerData array at the index number represented by the row selected in your UIPickerView Object.