使用NSUserDefaults

时间:2015-08-10 19:17:59

标签: ios swift nsuserdefaults

我正在尝试使用NSUserDefaults在swift中加载我保存的高分,但是它只是加载,我已经完成了尽可能多的教程,但它离开了我我的Highscore不想加载我的头。有人能够发现原因吗?

以下所有代码均位于GameScene.Swift

override func didMoveToView(view: SKView) {

    highScoreLabelNode.fontName = "Helvetica-Bold"
    highScoreLabelNode.position = CGPoint(x: self.frame.size.width / 2.6, y: self.frame.size.height / 1.3 )
    highScoreLabelNode.fontSize = 20
    highScoreLabelNode.alpha = 0.2
    highScoreLabelNode.zPosition = -30
    highScoreLabelNode.text = "Highscore \(score)"

    var highScoreDefault = NSUserDefaults.standardUserDefaults()
        if (highScoreDefault.valueForKey("HighScore") != nil){
    highScore = highScoreDefault.valueForKey("Highscore") as! NSInteger!
    highScoreLabelNode.text = NSString(format: "Highscore : %i", highScore) as String
     }
        self.addChild(highScoreLabelNode)

}

override func update(currentTime: CFTimeInterval) {

    if (score > highScore) {
        highScore = score
        highScoreLabelNode.text = NSString(format: "Highscore : %i", highScore) as String

        var highscoreDefault = NSUserDefaults.standardUserDefaults()
        highscoreDefault.setValue(highScore, forKey: "Highscore")
        highscoreDefault.synchronize()
    }
}

3 个答案:

答案 0 :(得分:3)

在您提供的代码中,您正在设置" Highscore"更新时,但试图获得" HighScore" (注意大写S)

这一行:

if (highScoreDefault.valueForKey("HighScore") != nil){

将其更改为:

if (highScoreDefault.valueForKey("Highscore") != nil){

答案 1 :(得分:0)

NSUserDefaults有一个读取和写入整数值的显式方法。

替换

var highScoreDefault = NSUserDefaults.standardUserDefaults()
if (highScoreDefault.valueForKey("HighScore") != nil){
    highScore = highScoreDefault.valueForKey("Highscore") as! NSInteger!
    highScoreLabelNode.text = NSString(format: "Highscore : %i", highScore) as String
}

let defaults = NSUserDefaults.standardUserDefaults()
highScore = defaults.integerForKey("Highscore")
highScoreLabelNode.text = "\(highScore)"

如果您将密钥注册为Apple recommends,则可以使用非可选变量

答案 2 :(得分:0)

值区分大小写,因此未找到值错误。您将价值存储为" Highscore"但是把它读作" HighScore",它将永远是空的。只需改变钥匙你是金色的:)

另外,不要使用!= nil,因为它无效并且不需要swift;相反,请使用if语法,如下所示:

if let highScore = NSUserDefaults.standardUserDefaults().valueForKey("Highscore") as? Int {
    highScoreLabelNode.text = String(format: "Highscore : %d", highScore)
} 

这使您的代码更具可读性,您会发现它更容易编写。您可以阅读更多关于"可选链接"在Swift Documentation

希望它有所帮助!