Swift - 使用NSUserDefaults保存高分 [英] Swift - Saving highscore using NSUserDefaults

查看:161
本文介绍了Swift - 使用NSUserDefaults保存高分的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用Swift制作游戏。我想使用NSUserDefaults保存用户的高分。我知道如何在我的AppDelegate文件中创建一个新的NSUserDefaults变量:

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:

let highscore: NSUserDefaults = NSUserDefaults.standardUserDefaults()

但是如何在我的视图控制器中设置/获取它?

But how do I set/get this in my view controllers?

推荐答案

首先,NSUserDefaults是一个字典(我认为是NSDictionary)。每个应用都有自己的用户默认值,因此您无法从任何其他应用访问用户默认值。

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
}

这篇关于Swift - 使用NSUserDefaults保存高分的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆