如何在Swift中增加和保存int值?

时间:2015-06-14 03:40:12

标签: ios swift nsuserdefaults

我试图跟踪用户在游戏中失去的次数。因此,对于每一次损失,它都会增加1.我也想保存它,以便用户可以看到他们丢失了多少次。现在我的代码第一次运行并转到一个但是如果我在游戏中输了之后它就会停留在1.我做错了什么?谢谢!

 class level1: SKScene, SKPhysicsContactDelegate, GKGameCenterControllerDelegate {

      var deathScore = 0


      override func didMoveToView(view: SKView) {

      var deathLabel = SKLabelNode()

      deathLabel = SKLabelNode(fontNamed: "LadyIce-3D")
      deathLabel.text = "100"
      deathLabel.zPosition = 14
      deathLabel.fontSize = 100
      deathLabel.fontColor = SKColor.darkTextColor()
      deathLabel.position = CGPointMake(self.size.width / 1.1, self.size.height / 1.4)
      deathLabel.hidden = true
      self.addChild(deathLabel)

      }



  if firstBody.categoryBitMask == HeroCategory && fourthBody.categoryBitMask == GameOverCategory {


    deathScore++
    deathLabel.hidden = false

        let defaults = NSUserDefaults()

        let saveDeaths = NSUserDefaults().integerForKey("saveNumberOfDeaths")
        if(deathScore > saveDeaths)
        {
            NSUserDefaults().setInteger(saveDeaths, forKey: "saveNumberOfDeaths")
        }
        var showNumberOfDeaths = defaults.integerForKey("saveNumberOfDeaths")




    deathLabel.text = String(showNumberOfDeaths)

     }

     }

1 个答案:

答案 0 :(得分:3)

您每次都声明一个新的var deathScore,初始化为0并递增它。它总是1。

UserDefaults.standard.set(UserDefaults.standard.integer(forKey: "saveNumberOfDeaths")+1, forKey: "saveNumberOfDeaths")

deathLabel.text = String(UserDefaults.standard.integer(forKey: "saveNumberOfDeaths"))