使用 NSUserdefaults 在游戏中保存分数

Save score in a game with NSUserdefaults

我制作了这个小应用程序 "How many fingers",用户必须在其中猜测计算机背后有多少根手指。现在我希望它能够使用 NSUserdefaults 保存用户分数,但它不起作用。这是我的代码现在的样子:

//
//  ViewController.swift
//  How many Fingers?
//
//  Created by Kevin Nguyen on 02.05.15.
//  Copyright (c) 2015 Kevin Nguyen. All rights reserved.
//

import UIKit

class ViewController: UIViewController {


    @IBOutlet var userGuess: UITextField!
    @IBOutlet var userScore: UILabel!
    @IBOutlet var userTotal: UILabel!
    @IBOutlet var result: UILabel!
    var score:Int = 0
    var totalGames:Int = 0

    @IBAction func resetScore(sender: AnyObject) {
        score = 0
        userScore.text = "0"
    }


    @IBAction func start(sender: AnyObject) {
        var userGuessInt = userGuess.text.toInt()
        var fingers = Int(arc4random_uniform(6))
        if userGuessInt <= 5 {
            if userGuessInt == fingers {
                result.text = "Great! You were right!"
                score++
                totalGames++
                userScore.text = "\(score)"
                userTotal.text = "\(totalGames)"
                println("User score is \(score); total games is \(totalGames)")
                NSUserDefaults.standardUserDefaults().setObject(score, forKey: "svScore")
                NSUserDefaults.standardUserDefaults().setObject(totalGames, forKey: "svTotalGames")
            } else {
                result.text = "Try Again!"
                println("User score is \(score); total games is \(totalGames)")
                totalGames++
                userTotal.text = "\(totalGames)"
                NSUserDefaults.standardUserDefaults().setObject(score, forKey: "svScore")
                NSUserDefaults.standardUserDefaults().setObject(totalGames, forKey: "svTotalGames")
            }

        } else{
            result.text = "Enter a number from 0 up to 5!"
        }
    }

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.
        if score != 0 {
            var score:Int = NSUserDefaults.standardUserDefaults().objectForKey("svScore")! as! Int
            userScore.text = "\(score)"
        }
        if totalGames != 0 {
            var totalGames:Int = NSUserDefaults.standardUserDefaults().objectForKey("svTotalGames")! as! Int
            userTotal.text = "\(totalGames)"
        }
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }

}
//To Save Highscore
NSUserDefaults.standardUserDefaults().setInteger(highScore, forKey: "highscore")
//To Call For Highscore
var highScore:Int = NSUserDefaults.standardUserDefaults().integerForKey("highscore")

当您的应用程序启动时,viewDidLoad 中的 score 始终是 0。所以你永远不会读取保存的数据(因为你的 if 条件)。您还应该在尝试使用它之前检查它是否存储了数据。

改成这样:

override func viewDidLoad() {
    super.viewDidLoad()

    if (NSUserDefaults.standardUserDefaults().objectForKey("svScore") != nil) {
        score = NSUserDefaults.standardUserDefaults().objectForKey("svScore")! as! Int
    }
    if score != 0 {
        userScore.text = "\(score)"
    }

    if (NSUserDefaults.standardUserDefaults().objectForKey("svTotalGames") != nil) {
         totalGames = NSUserDefaults.standardUserDefaults().objectForKey("svTotalGames")! as! Int
    }
    if totalGames != 0 {
        userTotal.text = "\(totalGames)"
    }
}

您可以像这样创建一个 HighscoreSaver-util class:

class HighscoreSaver {
    private let defaults = NSUserDefaults.standardUserDefaults()
    private let highscoreKey = "highscore-saver-key-item"
    private var highscore:Int = 0

    private func updateHighscore(score:Int){
        highscore += score
        if defaults.integerForKey(highscoreKey) < highscore{
            defaults.setInteger(highscore, forKey: highscoreKey)
        }
    }

    func add(score scoreToAdd:Int){
        updateHighscore(scoreToAdd)
    }

    func reset(){
        defaults.removeObjectForKey(highscoreKey)
    }

    func currentHighscore() -> Int{
        return highscore
    }
}

用法是这样的:

var high = HighscoreSaver()

//Adds scorevalue to current score
high.add(score: yourScoreToAddToCurrent)

//Resets the score to 0
high.reset()

//Gets current score
high.currentHighscore()