OGeek|极客世界-中国程序员成长平台

标题: ios - 当 viewController 转到另一个 tableViewController 时,我如何保存字符串的值 [打印本页]

作者: 菜鸟教程小白    时间: 2022-12-12 23:33
标题: ios - 当 viewController 转到另一个 tableViewController 时,我如何保存字符串的值

嗯,这个问题听起来很奇怪,但我找不到更好的方法。

我很确定这是一个基本错误,但我被卡住了。

我有一个主视图 Controller ,有 2 个按钮可以通向 2 个不同的 tableViewController。

我将使用这两种选择。

但是当我从一个 TableView 中获取选定的索引并转到下一个时,第一个的值变为空。

if (tempFromLocationString!=NULL) {
    //tempFromLocationString=@"asd";
    fromLocationLabel.text=tempFromLocationString;
}
if (tempToLocationString!=NULL) {
    toLocationLabel.text=tempToLocationString;
}

这就是我从 tableView 到 View Controller 的方式

- (void)prepareForSegueUIStoryboardSegue *)segue senderid)sender
{

    if ([[segue identifier] isEqualToString"fromLocationSegue"])
    {

         NSLog(@"%@",selectionString);
ViewController *vc = [segue destinationViewController];
        vc.tempFromLocationString=selectionString;


}
}

这就是我获取所选单元格值的方式。

- (void) tableViewUITableView *)tableView didSelectRowAtIndexPathNSIndexPath *)indexPath{


   selectionString=[fromLocationArray objectAtIndex:indexPath.row];

    NSLog(@"%@",selectionString);


}

这是我的代码。我得到带有 segues 的临时字符串,我在 View 中应用这些代码确实加载了。

.h 文件中声明的所有 NSStrings。

流程是这样的;

用户进入应用程序, 选择一个按钮, 转到第一个 TableView Controller 选择一个位置, 单击确定按钮并使用 segue ( selectionString) 返回到第一个 View Controller 标签被适本地设置为 selectionString

用户点击下一步按钮, 转到选择 TableView 选择一个位置 单击确定并返回第一个 View Controller ,现在第二个标签被适本地设置为 selectionString 但现在第一个被删除并且字符串变为空



Best Answer-推荐答案


好的 您的应用流程

案例1

  1. 用户进入应用-正确

  2. 选择一个按钮- 正确

  3. 转到第一个 TableViewController 选择一个位置 - 正确

  4. 点击确定按钮- 正确

  5. 然后使用 segue 回到第一个 View Controller (selectionString) 标签设置为 selectionString 适当 - 不正确

    第 5 步不正确,为什么?

    Answer - 因为您在 tableViewController 中选择之后再次推送 ViewController,因为您的 ViewController 已经存在于堆栈中,所以在这里而不是使用 segue,您应该使用从 ViewController 获取的相同引用弹出 View Controller 。

案例2

  1. 用户点击下一步按钮 - 正确

  2. 转到选择 TableView 选择位置点击确定 - 正确

  3. 现在返回第一个 View Controller ,第二个标签被适本地设置为 selectionString 但现在第一个被删除并且字符串变为空 - 不正确

    <

第 3 步不正确,与 Case1 相同。

Answer- 同样,您实际上并没有后退,而是在前进,所以发生的情况是您在选择时创建了一个新的 ViewController 实例,它没有先前选择的值。

解决方案

  1. 在每个相应的 tableViewController 中分别创建 NSString 属性,与在 ViewController 中的相同。

  2. 当你从 ViewController 中分离 tableViewController 时,分配属性就像

      TableViewController *vc = [segue destinationViewController];
      vc.tempFromLocationString=self.tempFromLocationString;
    
  3. 在 tableviewcontroller 中进行选择时,请执行以下操作

      self.tempFromLocationString=selectionString;
      [self.navigationController popViewController:YES];
    
  4. 现在不要在 ViewController 中的 ViewDidLoad 中赋值,而是在 ViewWillAppear 中进行赋值。

希望对你有帮助。

关于ios - 当 viewController 转到另一个 tableViewController 时,我如何保存字符串的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24505652/






欢迎光临 OGeek|极客世界-中国程序员成长平台 (http://sqlite.in/) Powered by Discuz! X3.4