问题
I want to keep a track of how many points have been scored overall in game over as many games as the person plays. For example, if a person plays the game 25 times and scores 100 each time then their total score would be 2500. This is the method I am using to increment the score in the game:
let waitScore = SKAction.waitForDuration(1.0) //add score every second
let incrementScore = SKAction.runBlock ({
++self.score
self.scoreLabel.text = "\(self.score)"}) //update score label with score
self.runAction(SKAction.repeatActionForever(SKAction.sequence([waitScore,incrementScore])))
The total score will be displayed in a different scene, so I guess I need to save the total score using NSUser defaults, load it in the game scene where the score is being counted and somehow add the loaded total score to the current score then save the total score?! I hope this makes sense.
回答1:
Define a convenience constant
totalScoreKey
somewhere outside a classlet totalScoreKey = "totalScore"
In the AppDelegate class register the key
totalScore
, for example in theinit
methodoverride init() { let userDefaults = NSUserDefaults.standardUserDefaults() let defaultValues = [totalScoreKey: 0] userDefaults.registerDefaults(defaultValues) }
getTotalScore()
reads and returns the total score.
The method can be implemented in any classfunc getTotalScore() -> Int { let userDefaults = NSUserDefaults.standardUserDefaults() return userDefaults.integerForKey(totalScoreKey) }
updateTotalScore()
reads the total score from user defaults adds the value inself.score
and writes the value back.
The method must be implemented in the class which contains the variablescore
func updateTotalScore() { let userDefaults = NSUserDefaults.standardUserDefaults() var totalScore = userDefaults.integerForKey(totalScoreKey) totalScore += self.score userDefaults.setInteger(totalScore, forKey: totalScoreKey) }
回答2:
Write:
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
[defaults setInteger:10 forKey:@"score"];
[defaults synchronize];
Read:
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
NSInteger score = [defaults integerForKey:@"score"];
来源:https://stackoverflow.com/questions/31771159/how-to-keep-a-total-of-how-many-points-have-been-scored-overall