0

我有一个 UIPickerView,在单独的视图 settingsViewController 中有很多行。选择一行后,将数据通过NSUSERDEFAULTS传递给我的MainViewController。但是,如果我返回 settingsViewController 并且不更改行,按下保存按钮 - pickerView 似乎发送值“nil”?

这是 UIPickerView 的代码和传递行的代码。

//PickerViewCode
    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
    [picker selectRow:[defaults integerForKey:@"pickerRow"] inComponent:0 animated:YES];
}

}

- (NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView {
return 1;

}

- (NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:  
(NSInteger)component {
{
    if ([skolor count] == 0)
        return 1;
    return [skolor count];
}}

- (NSString *)pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row 
forComponent:(NSInteger)component {
return [skolor objectAtIndex:row];
}


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

NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
[defaults setInteger:row forKey:@"pickerRow"];

//Passing pickerViewValue
- (IBAction)selectedRow:(id)sender {

SchoolSoftViewController2 *vc1 = [self.storyboard 
instantiateViewControllerWithIdentifier:@"webview1"];
NSString *urlString = [valdSkola absoluteString];
[[NSUserDefaults standardUserDefaults] setObject:urlString  forKey:@"UserURL"];
[self presentViewController:vc1 animated:YES completion:nil];

}
4

2 回答 2

0

尝试设置选择器选择的值。像这样。

int row = [pickerView selectedRowInComponent:COMPONANT_INDEX]; NSString *str = [YOUR_ARRAY objectAtIndex:row];//如果数组为空可能会崩溃

[[NSUserDefaults standardUserDefaults] setObject:str forKey:@"UserURL"]; [[NSUserDefaults standardUserDefaults] 同步];

在你的情况下, NSString *urlString = [valdSkola absoluteString]; // 这是返回一个 nil

于 2013-08-24T05:15:03.110 回答
0

NSUserDefaults 在使用 setObject:forKey: 方法调用设置后不会立即保存信息。要强制它保存,请在将 urlString 设置为默认值之后但在呈现视图控制器之前告诉它同步。

NSString *urlString = [valdSkola absoluteString];
[[NSUserDefaults standardUserDefaults] setObject:urlString  forKey:@"UserURL"];
[[NSUserDefaults standardUserDefaults] synchronize];
[self presentViewController:vc1 animated:YES completion:nil];

以及您设置行的位置:

NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
[defaults setInteger:row forKey:@"pickerRow"];
[defaults synchronize];
于 2013-08-22T21:44:16.480 回答