swift - 为什么我的对象没有转移到下一个 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)
}
}
解决方案
正如@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 = item
at 行// 2.
。
推荐阅读
- python - 在python中测试可变性
- java - 尝试创建新对象时构造函数未定义错误
- vim - vim-LanguageTool 和 vim-grammarous 不起作用
- apache-kafka - 启用rocksdb压缩后不正确的ktable聚合
- javascript - Get the highlighted/selected text in CKEDITOR 5
- python - 使用python中的命令在windows中压缩文件
- r - 如何在 R 中使用多列进行累积总和?
- pine-script - 未声明的标识符“shigh”;交易视图(pinescripts)
- python - 在 FB-Prophet 上处理不同的数据频率
- ios - React Native App 未安装在 ios 模拟器中