xcode 使用 NSuserdefaults 在 Swift 和 Sprite Kit 中设置 HighScore
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/25587299/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Setting Up HighScore in Swift and Sprite Kit using NSuserdefaults
提问by georgiohelou
I am building a swift game and a need to set up a highscore , i have been trying to figure out how to do it for a while. So please can you tell me how to search this library to see if there is a already saved high score and then compare it to the user's score. I have tried coming out with this but it won't work. Please Help and be as clear as possible. Giving me example code would be extremely appreciated.
我正在构建一个 swift 游戏并且需要设置一个高分,我一直试图弄清楚如何做到这一点。所以请您告诉我如何搜索该库以查看是否有已经保存的高分,然后将其与用户的分数进行比较。我试过提出这个问题,但它行不通。请帮助并尽可能清楚。给我示例代码将不胜感激。
if let highscore: AnyObject = NSUserDefaults.valueForKey("highscore") {
var savedScore: Int = NSUserDefaults.standardUserDefaults().objectForKey("highScore") as Int
if ( savedScore < Score) {
var highscore = Score
NSUserDefaults.standardUserDefaults().setObject(highscore, forKey:"highscore")
NSUserDefaults.standardUserDefaults().synchronize() }
}
else {
var highscore = Score
NSUserDefaults.standardUserDefaults().setObject(highscore, forKey:"highscore")
NSUserDefaults.standardUserDefaults().synchronize()
}
回答by Imanou Petit
Create a new iOS project in Xcode by using the Single View Applicationtemplate. Then, replace the content of ViewController.swift
with the following code:
使用Single View Application模板在 Xcode 中创建一个新的 iOS 项目。然后,将 的内容替换ViewController.swift
为以下代码:
import UIKit
class ViewController: UIViewController {
var generator = [6, 12, 8].generate()
override func viewDidLoad() {
super.viewDidLoad()
let button = UIButton(type: .System)
button.setTitle("Button", forState: .Normal)
button.addTarget(self, action: "newScore", forControlEvents: .TouchUpInside)
button.translatesAutoresizingMaskIntoConstraints = false
view.addSubview(button)
// Auto layout code using anchors (requires iOS9+)
let horizontalConstraint = button.centerXAnchor.constraintEqualToAnchor(view.centerXAnchor)
let verticalConstraint = button.centerYAnchor.constraintEqualToAnchor(view.centerYAnchor)
NSLayoutConstraint.activateConstraints([horizontalConstraint, verticalConstraint])
// Print NSUserDefaults's highscore value when app is launched
print("highscore:", NSUserDefaults.standardUserDefaults().integerForKey("highscore"))
}
func newScore() {
guard let score = generator.next() else { return }
print("current score:", score)
//Check if score is higher than NSUserDefaults stored value and change NSUserDefaults stored value if it's true
if score > NSUserDefaults.standardUserDefaults().integerForKey("highscore") {
NSUserDefaults.standardUserDefaults().setInteger(score, forKey: "highscore")
NSUserDefaults.standardUserDefaults().synchronize()
}
print("highscore:", NSUserDefaults.standardUserDefaults().integerForKey("highscore"))
}
}
Build and run the project on your iPhone or on the simulator. The Xcode console will print 0, which is the current value for NSUserDefaults.standardUserDefaults().integerForKey("highscore")
.
在您的 iPhone 或模拟器上构建并运行项目。Xcode 控制台将打印 0,这是NSUserDefaults.standardUserDefaults().integerForKey("highscore")
.
Now, click on the button. This will set the value of score
to 6
and, because 6 > 0
, NSUserDefaults.standardUserDefaults().integerForKey("highscore")
will get this new value.
现在,单击按钮。这将设置的值score
,以6
和,因为6 > 0
,NSUserDefaults.standardUserDefaults().integerForKey("highscore")
就会获得这个新的价值。
Click once again on the button. This will set the value of score
to 12
. You will immediately see in the console that NSUserDefaults.standardUserDefaults().integerForKey("highscore")
gets this new value.
再次单击按钮。这会将 的值设置score
为12
。您将立即在控制台中看到NSUserDefaults.standardUserDefaults().integerForKey("highscore")
获取此新值的信息。
Now, if you change the value of score
to 8
by clicking on the button, you will see that NSUserDefaults.standardUserDefaults().integerForKey("highscore")
still has a value of 12
because 8 < 12
.
现在,如果您通过单击按钮更改score
to的值8
,您将看到它NSUserDefaults.standardUserDefaults().integerForKey("highscore")
的值仍然是12
因为8 < 12
。
If you rebuild your project and relaunch it, you will see that NSUserDefaults.standardUserDefaults().integerForKey("highscore")
is persistent (its value is still 12 and has not been reset). Therefore, NSUserDefaults
can be a perfect tool in order to store your players highest scores.
如果你重建你的项目并重新启动它,你会看到它NSUserDefaults.standardUserDefaults().integerForKey("highscore")
是持久的(它的值仍然是 12 并且没有被重置)。因此,NSUserDefaults
可以成为一个完美的工具来存储你的玩家最高分。
Extra tip
额外小费
NSUserDefaults.standardUserDefaults().integerForKey("highscore")
always return an Int
(if you haven't set it by yourself, it will return 0
, not nil
). Thus, you dont need to / can't use optional binding with it. If you really want to deal with an optional value return, you will prefer NSUserDefaults.standardUserDefaults().objectForKey("highscore") as? Int
.
NSUserDefaults.standardUserDefaults().integerForKey("highscore")
总是返回 an Int
(如果你没有自己设置它,它会返回0
,而不是nil
)。因此,您不需要/不能对它使用可选绑定。如果你真的想处理一个可选的值返回,你会更喜欢NSUserDefaults.standardUserDefaults().objectForKey("highscore") as? Int
.
回答by jigar parmar
var defaults=NSUserDefaults()
var highscore=defaults.integerForKey("highscore")
if(Score>highscore)
{
defaults.setInteger(Score, forKey: "highscore")
}
var highscoreshow=defaults.integerForKey("highscore")
lblHighScore.text="\(highscoreshow)"
println("hhScore reported: \(lblHighScore.text)")
lblPlayScore.text="\(Score)"
println("play reported: \(lblPlayScore.text)")