How can I save a second row of UIPickerView to NSUserDefaults?

送分小仙女□ 提交于 2019-12-08 06:45:54

问题


I have pickerView with two rows and I need to save position of both to NSUserDefaults. I have successful saved first row with this code:

- (void)pickerView:(UIPickerView *)thePickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component {    
    NSInteger selectedRow = [thePickerView selectedRowInComponent:0];

    [[NSUserDefaults standardUserDefaults] setInteger:selectedRow forKey:@"picker"];
}

And I don't get how to add a second one.

With this code I bring back the position:

-(void)viewWillAppear: (BOOL) animated {
    NSUserDefaults *pickerViewSelectionDefaults = [NSUserDefaults standardUserDefaults];
[picker selectRow:[pickerViewSelectionDefaults integerForKey:@"picker"] inComponent:0 animated:YES];
[picker selectRow:[pickerViewSelectionDefaults integerForKey:@"picker"] inComponent:1 animated:YES];
}

回答1:


Try this:

- (void)pickerView:(UIPickerView *)thePickerView didSelectRow:(NSInteger)row
             inComponent:(NSInteger)component {    
    NSInteger selectedRow = [thePickerView selectedRowInComponent:component];
    NSString *key = [NSString stringWithFormat:@"picker%d", component];

    [[NSUserDefaults standardUserDefaults] setInteger:selectedRow forKey:key];
}

and this

-(void)viewWillAppear: (BOOL) animated {
    NSUserDefaults *pickerViewSelectionDefaults = [NSUserDefaults standardUserDefaults];
    [picker selectRow:[pickerViewSelectionDefaults integerForKey:@"picker0"] 
        inComponent:0 animated:YES];
    [picker selectRow:[pickerViewSelectionDefaults integerForKey:@"picker1"] 
        inComponent:1 animated:YES];
}



回答2:


Add them with separate keys.

- (void)pickerView:(UIPickerView *)thePickerView didSelectRow:(NSInteger)row inComponent:   (NSInteger)component {    
NSInteger selectedRow = [thePickerView selectedRowInComponent:0];

[[NSUserDefaults standardUserDefaults] setInteger:selectedRow forKey:@"pickerRow1"];
[[NSUserDefaults standardUserDefaults] setInteger:selectedRow forKey:@"pickerRow2"];
}


来源:https://stackoverflow.com/questions/6034276/how-can-i-save-a-second-row-of-uipickerview-to-nsuserdefaults

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!