我正在使用Swift制作游戏。我想使用NSUserDefaults保存用户的高分。我知道如何在AppDelegate文件中创建一个新的NSUserDefaults变量:
let highscore: NSUserDefaults = NSUserDefaults.standardUserDefaults()
但是如何在我的视图控制器中设置/获取它?
答案 0 :(得分:35)
首先,NSUserDefaults是一本字典(我认为是NSDictionary)。每个应用都有自己的用户默认值,因此您无法从任何其他应用访问用户默认值。
如果用户(玩游戏的人)创造了新的高分,那么你必须保存这样的高分:
let highscore = 1000
let userDefaults = NSUserDefaults.standardUserDefaults()
userDefaults.setValue(highscore, forKey: "highscore")
userDefaults.synchronize() // don't forget this!!!!
然后,当你想获得用户所做的最高分时,你必须从字典中“读取”这样的高分:
if let highscore = userDefaults.valueForKey("highscore") {
// do something here when a highscore exists
}
else {
// no highscore exists
}
答案 1 :(得分:11)
在Swift 3.0中
let highScore = 1000
let userDefults = UserDefaults.standard //returns shared defaults object.
保存:
userDefults.set(highScore, forKey: "highScore") //Sets the value of the specified default key to the specified integer value.
检索:
if let highScore = userDefults.value(forKey: "highScore") { //Returns the integer value associated with the specified key.
//do something here when a highscore exists
} else {
//no highscore exists
}
答案 2 :(得分:0)
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)")
答案 3 :(得分:0)
快捷键4
设置值
UserDefaults.standard.set("TEST", forKey: "Key")
// setString
检索
UserDefaults.standard.string(forKey: "Key")
// getString
删除
UserDefaults.standard.removeObject(forKey: "Key")
答案 4 :(得分:-2)
您可以使用以下代码:
// Your score var
var score:Int = 0
//save
score = NSUserDefaults.standardUserDefaults().setInteger(score, forKey: "score")
// load without starting value nil problems
if NSUserDefaults.standardUserDefaults().setIntergerForKey:("score") != nil {
score = NSUserDefaults.standardUserDefaults().setIntergerForKey:("score")
}