简体   繁体   中英

Save score in a game with NSUserdefaults

I've made this little app "How many fingers" where the user has to guess how many fingers the computer is holding behind it's back. Now I want it to be able to save the users score with NSUserdefaults, but it's not working. Here is how my code looks right now:

//
//  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.
    }

}

When your application starts the score in viewDidLoad is always 0 . So you'll never read the saved data (because of your if condition). You should also check it there is data stored before you try to use it.

Change it like that:

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)"
    }
}
//To Save Highscore
NSUserDefaults.standardUserDefaults().setInteger(highScore, forKey: "highscore")
//To Call For Highscore
var highScore:Int = NSUserDefaults.standardUserDefaults().integerForKey("highscore")

You could create a HighscoreSaver-util class like that:

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
    }
}

The usage would be like that:

var high = HighscoreSaver()

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

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

//Gets current score
high.currentHighscore()

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