首页 > 解决方案 > 为什么我的对象没有转移到下一个 VC?

问题描述

我正在尝试使用按钮将我的对象从 HockeyDetailVC 转移到我的 FavouritesVC 但是当我到达我的第二个 VC FavouritesVC 时我的对象为零。当我用我的 func transferObj() 在我的 firstVC 中设置变量时,为什么会这样?

曲棍球细节VC

var item: CurrentPlayers?

override func viewDidLoad() {
        super.viewDidLoad()
        gonnaLoadView()
        tableV.bounces = false
        tableV.alwaysBounceVertical = false
        favButton.layer.cornerRadius = 10
        print(item)    *//prints my current players object*
    }

   func transferObj() {
        let otherVC = FavouritesVC()
        otherVC.currentFav = item
        print(item).  *//prints my current player object*
    }

  @IBAction func addToFav(_ sender: Any) {
    transferObj()
    print("Favourite button Pressed")
}

最爱VC

  var currentFav: CurrentPlayers?

  override func viewDidLoad() {
    super.viewDidLoad()
    if currentFav == nil {
    //display nil
    self.tableView.separatorStyle = UITableViewCell.SeparatorStyle.none
    print(favArr)    *//prints empty array*
    print(currentFav) *//nil*
    } else {
    favArr.append(currentFav!)
    print(favArr)
    }
}

标签: swiftxcode

解决方案


正如@Martin 所说,let otherVC = FavouritesVC()创建控制器的一个新实例,但它不是您最终将显示的实例。因此,您实际上是在设置currentFav一个永远不会实际显示的随机 FavouritesVC,而您最终导航到的那个它的currentFav属性仍未设置。

要设置适当的 FavouritesVC 实例,您需要以多种方式之一访问它(取决于您呈现它的方式)。如果是通过segue,那么你可以在prepare(for segue: sender:)方法中引用它。(当你创建一个 Cocoa Touch Class 文件时,下面的方法模板是预先填充的。正如它所说,使用 segue.destination 引用新的视图控制器。)

/*
    // MARK: - Navigation

    // In a storyboard-based application, you will often want to do a little preparation before navigation
    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        // Get the new view controller using segue.destination.
        // Pass the selected object to the new view controller.
    }
    */

或者,如果您以编程方式创建并呈现新的视图控制器,例如

// 1.
let otherVC = storyboard?.instantiateViewController(withIdentifier: "yourFavouritesVCIdentifier")

// 2.

// 3.
self.show(otherVC, sender: self)

你可以插入你的otherVC.currentFav = itemat 行// 2.


推荐阅读