Trenton Tyler Trenton Tyler - 5 months ago 15
Swift Question

Update NSUserDefaults for a variable

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()

Answer

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