我们如何在 firstVC 中获取 secondVC json 值而不快速进入 secondVC

Posted

技术标签:

【中文标题】我们如何在 firstVC 中获取 secondVC json 值而不快速进入 secondVC【英文标题】:How can we get secondVC json value in firstVC without going to secondVC in swift 【发布时间】:2019-10-02 11:34:40 【问题描述】:

我的 firstVC json 包含所有其他视图控制器 json id...在这里我想要在推送到其他视图控制器之前我需要将它与 home home json id 进行比较,其中 2 个 id 相同我需要推送 thatVC .. 所以在这里无需使用任何其他视图控制器,我们如何才能让他们的 id 在 homeVC 中进行比较...请在这里帮助我。

我尝试了两种方法:

1) 在 secondVC 中声明变量并为其分配 secondVC id 值并在 firstVC 中调用它

在第一个VC代码中:

let goVC = self.storyboard?.instantiateViewController(withIdentifier: "SecondViewController") as? SecondViewController

var goId: String = goVC.secndId ?? ""
print("the goid is \(goId)")// getting nil
if(goId == allIdArray)

    self.navigationController?.pushViewController(goVC, animated: true)

在第二个VC中:

var secndId: String?
secndId = jsonObj["sid"] as? String

2) 使用钥匙串包装器存储 secondVC json id 并在 firstVC 中检索它

首先:

let goVC = self.storyboard?.instantiateViewController(withIdentifier: "SecondViewController") as? SecondViewController

let goId: String = KeychainWrapper.standard.string(forKey: "sid") ?? ""
print("the goid is \(goId)")// getting nil
if(goId == allIdArray)

    self.navigationController?.pushViewController(goVC, animated: true)

在第二个VC中:

var secndId: String?
self.secndId = jsonObj["sid"] as? String
KeychainWrapper.standard.set(self.secndId ?? "", forKey: "sid")

这里allIdArray包含所有的VC id,而sid是secondVC json id

在这两种情况下我都得到了 nil 为什么?我想比较 firstvc 中的 secondvc id 而不去 secondvc。

请在上面的代码中帮助我。

【问题讨论】:

您的 secondVC 未初始化,因此其中的所有数据和所有方法尚未运行,因此未为您的变量分配任何 ID。我不确定我是否理解您要完成的工作,但您可以创建一个包含视图控制器类型的字典。我现在就写一个回复。 【参考方案1】:

你的整个逻辑设计不是很好,但是如果我要直接回答你的问题,并且考虑到解释也不是很好,这里给你一个建议:

  let vcID = 1

  let viewControllers = [1 : FirstVC.self, 2 : SecondVC.self, 3 : ThirdVC.self]
  for (id, vcType) in viewControllers 
     if id == vcID 
         //assuming that you assign storyboard identifiers exactly matching classes' names, otherwise this guard statement won't succeed
         guard let goToVC = storyboard?.instantiateViewController(withIdentifier: "\(vcType)") else  return 
         //if you need to pass any data before you present this VC, then you will need to safely cast into known VC types
         self.present(goToVC, animated: true, completion: nil)
     
  

【讨论】:

以上是关于我们如何在 firstVC 中获取 secondVC json 值而不快速进入 secondVC的主要内容,如果未能解决你的问题,请参考以下文章

当你在firstVC时如何在secondVC中运行一个函数?

在 FirstVC 中选择单元格后,如何为 SecondVC 中的每个单元格调用按钮操作?

无法使用 segue 将值从 FirstVC 传递到 SecondVC

Swift 4,加载下一个 ViewController

如何将两个视图控制器显示为模态但仅对第二个进行动画转换?

如何在 React 中执行返回功能 [重复]