0

So im trying to show a score on a scene using NSUserDefaults using the below:

var savedScore: Int = NSUserDefaults.standardUserDefaults().objectForKey("HighestScore") as! Int
let score = SKLabelNode()
    score.text = toString(savedScore)
    score.fontName = "Menlo-Regular";
    score.fontColor = UIColor.blackColor();
    score.position = CGPointMake(self.frame.size.width * 0.3, self.frame.size.height / 2)
    self.addChild(score)

But the first time this is ran, because there isn't anything in "HighestScore" yet, its crashing the app for trying to load a nil value. How can i have the score label show 0 the very first time this scene is ran, and then show whatever is in "HighestScore" every other time after.

user3593148
  • 505
  • 1
  • 3
  • 14

1 Answers1

1

You should be using integerForKey: instead of objectForKey: in this particular case. Change:

var savedScore: Int = NSUserDefaults.standardUserDefaults().objectForKey("HighestScore") as! Int

to:

var savedScore = NSUserDefaults.standardUserDefaults().integerForKey("HighestScore")

That will set savedScore to zero if it doesn't exist in the user defaults.

Good Doug
  • 2,072
  • 15
  • 12