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.
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)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.