Swift - Saving highscore using NSUserDefaults

后端 未结 5 1640
天命终不由人
天命终不由人 2020-11-28 15:27

I\'m using Swift to make a game. I want to save the users high score using NSUserDefaults. I know how to create a new NSUserDefaults variable in my AppDelegate file:

5条回答
  •  感情败类
    2020-11-28 15:34

    At first, NSUserDefaults is a dictionary (NSDictionary I think). Every app has its own user defaults, so you cannot access the user defaults from any other app.

    If the user (the one who plays your game) makes a new highscore, you have to save that highscore like this:

    let highscore = 1000
    let userDefaults = NSUserDefaults.standardUserDefaults()
    userDefaults.setValue(highscore, forKey: "highscore")
    userDefaults.synchronize() // don't forget this!!!!
    

    Then, when you want to get the best highscore the user made, you have to "read" the highscore from the dictionary like this:

    if let highscore = userDefaults.valueForKey("highscore") {
        // do something here when a highscore exists
    }
    else {
        // no highscore exists
    }
    

提交回复
热议问题