简体   繁体   English

Swift3 | Spritekit | 具有相同userdefaults键的两个不同的NSInteger返回错误的保存值

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

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. 对于关卡星,返回的值是1000,而应为3。 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. 但是我不明白为什么...这些值已设置为不同的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)    

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM