应用关闭或查看更改时,高分会重置。如何在Swift中永久保留高分?

时间:2015-10-30 15:53:03

标签: ios swift2 nsuserdefaults

实例变量:

var Score: Int64 = 0

 var highscore: Int64 = 0
      func saveHighScore(high:Int) {
        NSUserDefaults.standardUserDefaults().setInteger(high, forKey:        "highscore")

    }
  func highScore() -> Int {
   NSUserDefaults.standardUserDefaults().integerForKey("highscore")
   } func resetHighScore() {NSUserDefaults.standardUserDefaults().removeObjectForKey("highscore")
    }

///METHOD. ALL OF THIS IS WORKING FINE. HIGH SCORE SHOWS AND UPDATES WHILE IN THE GAME.

  override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
    // Dispose of any resources that can be recreated.
  }
 @IBAction func Ans1(sender: AnyObject) {
    if(CorrectAnswer) == "1" {

        // Calculate the number of points
        Score += 10
        scoreLabel.text = "Score:\(Score)"
        if (Score > highscore) {
            highscore = Score
            highScoreLabel.text = NSString(format: "High Score : %i",    highscore) as String
        }

我需要在这里添加任何内容吗?对于要在重新启动应用程序时保存和重新加载的数据?

3 个答案:

答案 0 :(得分:0)

在代码的开头,变量' highscore'重置为0.你应该使用' if'声明是否在nsuserdefaults中有一个带有' highscore'的键的整数,如果没有,则设置键的值' highscore'为0,否则,将变量highscore设置为等于键' highscore'的值。我提前为缺乏代码而道歉。

答案 1 :(得分:0)

您似乎永远不会调用您的方法saveHighScore()highscore()。相反,每次加载视图时,highscore变量都设置为0.

viewDidLoad()viewDidAppear()等生命周期方法中,您必须调用并设置它,如下所示:highscore = highscore()。这应该获取用户默认值并在视图中将highscore变量设置为保存的内容。

didReceiveMemoryWarning()或更好viewWillDisappear(),您应致电saveHighScore(highscore)

这样,您应该始终保存所有进度并通过关闭并重新打开应用程序来保持这些进度。

答案 2 :(得分:0)

您正在寻找NSUserDefaults:

let highscore = 1000
let userDefaults = NSUserDefaults.standardUserDefaults()
userDefaults.setValue(highscore, forKey: "highscore")
userDefaults.synchronize()

参考:Swift - Saving highscore using NSUserDefaults