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

查看:31
本文介绍了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天全站免登陆