1

This is my code on the view controller with the total score:

import UIKit

var playerName = ""
var totalScore = 0
var bestPlayer = "Taipan"
var highScore = 100

var myNumber: NSInteger = highScore
var myName: NSString = bestPlayer

class StartVC: UIViewController, UITextFieldDelegate {

    override func viewDidLoad() {
        super.viewDidLoad()
    }

    @IBOutlet weak var lblPlayerName: UILabel!

    @IBOutlet weak var lblNameScore: UILabel!

    @IBOutlet weak var txtPlayerName: UITextField!

    @IBAction func btnPlay(sender: UIButton) {
        if txtPlayerName.text == "" {
            lblPlayerName.text = "Please enter your name!"
        } else {
            playerName = txtPlayerName.text
            performSegueWithIdentifier("StartingStatsVC", sender: self)
        }
    }

    func textFieldShouldReturn(textField: UITextField) -> Bool {
        txtPlayerName.resignFirstResponder()
        return true
    }

    override func touchesBegan(touches: NSSet, withEvent event: UIEvent) {
        self.view.endEditing(true)
    }

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

    override func viewWillAppear(animated: Bool) {
        NSUserDefaults.standardUserDefaults().setObject(myNumber, forKey: "fixedHighScore")
        NSUserDefaults.standardUserDefaults().setObject(myName, forKey: "fixedPlayerName")
        NSUserDefaults.standardUserDefaults().synchronize()

        var myscore: AnyObject? = NSUserDefaults.standardUserDefaults().objectForKey("fixedHighScore")
        var myplayer: AnyObject? = NSUserDefaults.standardUserDefaults().objectForKey("fixedPlayerName")
        NSUserDefaults.standardUserDefaults().synchronize()

        lblNameScore.text = String(myplayer as NSString) + ": " + String(myscore as NSInteger)
    }
}

This is the code in a different view controller which will replace the highscore and bestplayer if the score is higher than the total:

if totalScore > Int(myNumber as NSNumber) {
        myNumber = totalScore
        myName = playerName
    }

Everything works except for saving the highscore and the bestplayer which is the whole point of using NSUserDefaults. Please let me know what to change for it to save correctly when the app is closed then brought up again.

1 Answers1

2

The problem is that you're setting the object of your two user default keys to myNumber and myName every time the view first appears (in viewWillAppear). You should use registerDefaults, to only add those initial values, if there aren't already values in the dictionary,

override func viewWillAppear(animated: Bool) {
        let dict = ["fixedHighSCore":myNumber, "fixedPlayerName":myName]
        NSUserDefaults.standardUserDefaults().registerDefaults(dict)
        NSUserDefaults.standardUserDefaults().synchronize()

        var myscore: AnyObject? = NSUserDefaults.standardUserDefaults().objectForKey("fixedHighScore")
        var myplayer: AnyObject? = NSUserDefaults.standardUserDefaults().objectForKey("fixedPlayerName")
        NSUserDefaults.standardUserDefaults().synchronize()

        lblNameScore.text = String(myplayer as NSString) + ": " + String(myscore as NSInteger)
    }

You also need to add the new values to the user defaults in your other controller (I don't know if you're already doing that, but just not showing it).

if totalScore > Int(myNumber as NSNumber) {
    NSUserDefaults.standardUserDefaults().setObject(totalScore, forKey: "fixedHighScore")
    NSUserDefaults.standardUserDefaults().setObject(playerName, forKey: "fixedPlayerName")
    NSUserDefaults.standardUserDefaults().synchronize()
}
rdelmar
  • 103,982
  • 12
  • 207
  • 218
  • Thank you very much, one last question. (I'm very new to this, so I apologize if it seems like I'm wasting your time. I did just troubleshoot theories for the last hour) How do I add the new values to the user defaults from the other controller? – Ethan Scott Miller Nov 20 '14 at 21:31
  • @EthanScottMiller, I've updated my answer to show you how. If you also need to update myNumber and myName from the other controller, you need to get a reference to the first controller, or use a protocol to send the new values back (but that's a topic for another question). – rdelmar Nov 20 '14 at 21:38