首页 > 解决方案 > 变量从另一个 swift 文件更改其值后返回 nil 值

问题描述

我正在尝试从另一个 Swift 文件中更改变量的值,但由于某种原因它不起作用并且返回 nil。

这是我尝试过的:

class ShowIssues: UIViewController, UITableViewDataSource, UITableViewDelegate {
  func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
    let si = self.storyboard?instantiateViewController(withIdentifier: "ShowIssueDetail") as! ShowIssueDetail
    si.idSelected = indexPath.row //Here I change the value of the variable
    performSegue(withIdentifier: "ShowIssueDetail", sender: self)
  }
}

ShowIssueDetail.swift:

class ShowIssueDetail: UITableViewController {
  var idSelected: Int! //This is the variable I want to change its value from the another swift file
    override func viewDidLoad() {
      print(idSelected) //Here it prints out nil instead of the selected row
    }
}

我也以这种方式尝试过,但同样的问题:

class ShowIssues: UIViewController, UITableViewDataSource, UITableViewDelegate {
  func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
    let si = ShowIssueDetail()
    si.idSelected = indexPath.row //Here I change the value of the variable
    performSegue(withIdentifier: "ShowIssueDetail", sender: self)
  }
}

我究竟做错了什么?

先感谢您!

注意:两个 swift 文件的类型不同,ShowIssues.swift 是 UIViewController,ShowIssueDetail 是 UITableViewController,我不知道它是否因此而不起作用。

标签: iosswiftvariablesnullsegue

解决方案


如果您在 Storyboard 中设置了 segue,则不应从代码中实例化目标视图控制器,Storyboard 将为您创建视图控制器。通过初始化另一个实例,您最终会在不会呈现给用户的实例上设置值。

您需要在prepare(for:)那里覆盖并设置该值。

class ShowIssues: UIViewController, UITableViewDataSource, UITableViewDelegate {
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        performSegue(withIdentifier: "ShowIssueDetail", sender: indexPath.row)
    }

    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        if segue.identifier == "ShowIssueDetail", let destinationVC = segue.destination as? ShowIssueDetail, let selectedId = sender as? Int {
          destinationVC.idSelected = selectedId
        }
    }
}

推荐阅读