简体   繁体   中英

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. Any suggestions?

You have instantiated leaderBoardVC , but never set the leadVC property. 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.

Frankly, I'd probably retire the leadVC property, altogether, which avoids this problem altogether. 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.


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).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM