0

I am trying to update the total number of times a person has jumped in my game but I am having some issues. Here are the variables for the jumps that occurred that game and the number of jumps that have happened overtime.

var timesJumped: Int = 0
var totalTimesJumped: Int = 0

I have a variable for NSUserDefaults so it remembers how many times even when app is shut down or closed.

var timesJumpedTotal = NSUserDefaults.standardUserDefaults().integerForKey("times jumped")

I have this block of code to run if timesJumpedTotal which should always run and be true so when I try and set the text to this timesJumpedTotal I am getting a blank text field. Is there a reason for this?

if timesJumpedTotal >= 0 {
        totalTimesJumped = totalTimesJumped + timesJumped
        NSUserDefaults.standardUserDefaults().setInteger(totalTimesJumped, forKey: "times jumped")
    }

In the SKScene where I want to display this statistic I have this code which sets the text of a node to the text of the totalTimesJumped:

let timesJumped = NSUserDefaults.standardUserDefaults().integerForKey("times jumped")
totalTimesjumped = childNodeWithName("TotalTimesJumped") as! SKLabelNode
totalTimesjumped.text = "\(totalTimesjumped)"

I am not sure why this is happening, does anybody have any idea?

I also tried this just moments ago.

totalTimesJumped = totalTimesJumped + timesJumped
timesJumpedTotal = totalTimesJumped
NSUserDefaults.standardUserDefaults().setInteger(timesJumped, forKey: "high score")
NSUserDefaults.standardUserDefaults().synchronize()
Mahendra
  • 8,448
  • 3
  • 33
  • 56
Trenton Tyler
  • 534
  • 1
  • 7
  • 20
  • Can you check with a breakpoint that NSUserDefaults.standardUserDefaults().setInteger(totalTimesJumped, forKey: "times jumped") is getting called, and that its being done before you try to fetch the value? Also, I would recommend you use a different approach for your keys, declare a constant let timesJumpedKey = "com.yourgame.timesjump" and use that as your key (the com.yourgame... is so that you can guarantee its uniqueness). – Daniel Ormeño Jun 10 '16 at 03:37

1 Answers1

1

Try changing

if timesJumpedTotal >= 0 {
    totalTimesJumped = totalTimesJumped + timesJumped
    NSUserDefaults.standardUserDefaults().setInteger(totalTimesJumped, forKey: "times jumped")
}

To:

if timesJumpedTotal >= 0 {
    totalTimesJumped = timesJumpedTotal + timesJumped
    NSUserDefaults.standardUserDefaults().setInteger(totalTimesJumped, forKey: "times jumped")
}

It appears that while you are getting the data from NSUserDefaults you are never actually using it to increment and rewrite the total. Naming your variables not so similarly would go a long way to helping see the problem. There may be a couple other places you have to change it

user3179636
  • 549
  • 3
  • 14