Swift3 | Spritekit | Two different NSIntegers with the same userdefaults key is returning wrong saved value

32 views Asked by At

Can anyone explain the following to this please and have a alternative? I've just put a simple example as my code is pretty large.

//Declare too variables
var levelStars = NSInteger()        
var levelScore = NSInteger()

//Load the variables
levelStars = UserDefaults.standard.integer(forKey: "1")
levelScore = UserDefaults.standard.integer(forKey: "1")

//Set the variables
levelStars = 3
levelScore = 1000

//Save the variables
UserDefaults.standard.set(levelStars, forKey: "1")
UserDefaults.standard.set(levelScore, forKey: "1")            

//Now when I call the following variable for levelStars
levelStars = UserDefaults.standard.integer(forKey: "1")
print(levelStars)    OUPUT: 1000  should be 3

The value returned is 1000 when it should be 3 for levelstars. I assume its because I used the same key and its just overwriting any previous userdefault with the same key value. However I do not understand why... The values have been set to different NSIntegers.

1

There are 1 answers

0
Amin Negm-Awad On

No, you do not need a dictionary. I think you need an example to understand it:

//Declare too variables
…

//Load the variables
levelStars = UserDefaults.standard.integer(forKey: "com.yourcomp.yourapp.levelStars")
levelScore = UserDefaults.standard.integer(forKey: "com.yourcomp.yourapp.levelScore")

//Set the variables
…

//Save the variables
UserDefaults.standard.set(levelStars, forKey: "com.yourcomp.yourapp.levelStars")
UserDefaults.standard.set(levelScore, forKey: "com.yourcomp.yourapp.levelScore")            

//Now when I call the following variable for levelStars
levelStars = UserDefaults.standard.integer(forKey: "com.yourcomp.yourapp.levelStars")
print(levelStars)