views:

74

answers:

1

Hi,

I have an UIPickerView with 2 components. I would like to save the user's selection and to apply it next time the pickerView is shown again.

Here's my code:


    - (void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component {

    NSUserDefaults *pickerViewSelectionDefaults = [NSUserDefaults standardUserDefaults];
    [pickerViewSelectionDefaults setInteger:row forKey:@"pickerViewSelectionKey"];
    [pickerViewSelectionDefaults synchronize];

}

}

And...


- (void)viewWillAppear:(BOOL)animated { 

    NSUserDefaults *pickerViewSelectionDefaults = [NSUserDefaults standardUserDefaults];
    [pickerView selectRow:[pickerViewSelectionDefaults integerForKey:@"pickerViewSelectionKey"] inComponent:0 animated:YES];

}

Thanks!

A: 

I fail to understand what your real issue is. Your code should work given that you only spin component 0 and not 1. There's an issue with storing the row for two components into one setting. If you spin component 1 to row 20 and then load the view it will most likely crash unless component 0 also has 20 rows.

Please provide an error message or something that indicate what is wrong. Also make sure that your viewWillAppear method is actually called.

Merrimack
The problem is that even with this NSUserDefaults code, each time the pickerView is shown, the selected index in both components is 0.Thank you for helping
Guy Dor
Are you sure that viewWillAppear is even called? Also make sure that the picker items has been populated at the time when viewWillAppear is executed.
Merrimack

related questions