[英]When my game ends I need to 'send' the variable holding the score to a table view controller
When my game ends I need to 'send' the variable holding the score to a table view controller. 游戏结束时,我需要将保存分数的变量“发送”到表视图控制器。 I tried doing this through 我尝试通过
//In LeaderboardTableVC.swift
var gameScore:Int! = 0
//In GameScene.swift
var leadVC: LeaderboardTableVC!
var score:Int = 0
func showLeaderboard(){
let sb = UIStoryboard(name: "Main", bundle: nil)
let leaderBoardVC = sb.instantiateViewController(withIdentifier: "leaderboard")
self.vc.navigationController?.pushViewController(leaderBoardVC, animated: true)
leadVC.gameScore = score
}
However when I run the code an error occurs: 'unexpectedly found nil while unwrapping an optional value ' on the 'leadVC.gameScore = score' line of code. 但是,当我运行代码时,会发生错误:'leadVC.gameScore = score'代码行上“意外发现nil,同时展开了一个可选值”。 Any suggestions? 有什么建议么?
You have instantiated leaderBoardVC
, but never set the leadVC
property. 您已经实例化了leaderBoardVC
,但是从未设置leadVC
属性。 Thus, leadVC
is still nil
when you try to set gameScore
, and thus it crashes when it tries to do the forced unwrapping of this implicitly unwrapped optional. 因此,当您尝试设置gameScore
时, leadVC
仍然nil
,因此当它尝试对此隐式解包的可选内容进行强制解包时,它会崩溃。
Frankly, I'd probably retire the leadVC
property, altogether, which avoids this problem altogether. 坦白说,我可能会完全淘汰leadVC
属性,从而完全避免了这个问题。 Why do you need this property? 为什么需要此属性? Anyway, you can do: 无论如何,您可以执行以下操作:
//In GameScene.swift
// var leadVC: LeaderboardTableVC!
var score:Int = 0
func showLeaderboard(){
let sb = UIStoryboard(name: "Main", bundle: nil)
guard let leaderBoardVC = sb.instantiateViewController(withIdentifier: "leaderboard") as? LeaderboardTableVC else {
fatalError("Either couldn't find scene with `leaderboard` identifier, or its base class was not `LeaderboardTableVC`")
}
leaderBoardVC.gameScore = score
self.vc.navigationController?.pushViewController(leaderBoardVC, animated: true)
}
Note, I'd probably set gameScore
before pushing to it. 注意,我可能会在gameScore
之前设置gameScore
。
Alternatively, if you really needed this property, you'd do: 或者,如果您确实需要此属性,则可以执行以下操作:
//In GameScene.swift
var leadVC: LeaderboardTableVC!
var score: Int = 0
func showLeaderboard() {
let sb = UIStoryboard(name: "Main", bundle: nil)
leadVC = sb.instantiateViewController(withIdentifier: "leaderboard")
leadVC.gameScore = score
self.vc.navigationController?.pushViewController(leadVC, animated: true)
}
This just begs the question of why do you want to keep a strong reference to this leadVC
(eg when you pop back, it's going to keep this in memory). 这只是一个问题,为什么您要对这个leadVC
保持强烈的引用(例如,当您弹出时,它将保留在内存中)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.