如何将数据存储到prepareForSeque中的NSUserDefaults

时间:2016-07-19 07:49:25

标签: ios objective-c

我正在尝试执行以下操作: 在设置场景更改设置中以及当我按下"返回"箭头,应存储已更改的数据。 我认为它应该在prepareForSeque方法中完成,如下所示:

- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    NSString* session_port = self.session_port.text;
    NSString* session_address = self.session_address.text;
    NSString* keep_alive_interval = self.session_keep_alive_interval.text;
    [[NSUserDefaults standardUserDefaults] setObject:session_port forKey:@"sessionPort"];
    [[NSUserDefaults standardUserDefaults] setObject:session_address forKey:@"sesssionAddress"];
    [[NSUserDefaults standardUserDefaults] setObject:keep_alive_interval forKey:@"keepAliveInterval"];
}

然而,当我再次进入设置窗口时,它似乎不起作用,数据仍然是标准数据。

有人能给我一个正确方向的暗示吗?

我在设置视图中加载数据,如下所示:

-(void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];

    self.session_address.text = [[NSUserDefaults standardUserDefaults] objectForKey:@"sesssionAddress"];
    self.session_port.text = [[NSUserDefaults standardUserDefaults] objectForKey:@"sessionPort"];
    self.session_keep_alive_interval.text = [[NSUserDefaults standardUserDefaults] objectForKey:@"keepAliveInterval"];

}

1 个答案:

答案 0 :(得分:0)

相反,在prepareForSeque的上述内容中,可以在viewWillDisappear中完成,如下所示:

-(void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    NSString* session_port = self.session_port.text;
    NSString* session_address = self.session_address.text;
    NSString* keep_alive_interval = self.session_keep_alive_interval.text;
    [[NSUserDefaults standardUserDefaults] setObject:session_port forKey:@"sessionPort"];
    [[NSUserDefaults standardUserDefaults] setObject:session_address forKey:@"sesssionAddress"];
    [[NSUserDefaults standardUserDefaults] setObject:keep_alive_interval forKey:@"keepAliveInterval"];
    [[NSUserDefaults standardUserDefaults] synchronize];
}

但是,这不是最佳解决方案,因为每次更改设置时都会访问NSUserDefaults。应该使用另一种方法在应用程序中传播更改,然后在应用程序关闭时存储数据。