我正在尝试保存收集的硬币并将该金额添加到用户收集的硬币总额中(在SpriteKit中)。使用当前代码,硬币当前不保存,并且总数中没有添加任何内容。我不知道为什么硬币没有保存,因为我没有在代码中看到任何明显的错误。任何帮助或解释为什么这不应该以它应该的方式工作将不胜感激。
var totalCoins = 0
var coin = 0
let totalCoinDefault = UserDefaults.standard()
totalCoins = totalCoinDefault.integer(forKey: "Totalcoin")
totalCoinLabel.text = "\(totalCoins)"
if ( coin > 0) {
totalCoins += self.coin
totalCoinLabel.text = String(format: "Totalcoin : %i", totalCoins)
let totalcoinDefault = UserDefaults.standard()
totalcoinDefault.setValue(totalCoins, forKey: "Totalcoin")
totalcoinDefault.synchronize()
}
func updateCoinTotal(){
coinLabel.text = String(self.coin)
totalCoinLabel.text = String(self.totalCoins)
let totalCoinDefault = UserDefaults.standard()
totalCoins = totalCoinDefault.integer(forKey: "")
totalCoinLabel.text = "\(totalCoins)"
if (self.coin > 0) {
totalCoins += self.coin
totalCoinLabel.text = NSString(format: "%i", totalCoins) as String
let totalcoinDefault = UserDefaults.standard()
totalcoinDefault.setValue(totalCoins, forKey: "")
totalcoinDefault.synchronize()
}
答案 0 :(得分:1)
这是您应该使用的更新代码:
totalCoins = NSUserDefaults.standardUserDefaults().integerForKey("Total Coins")
totalCoinLabel.text = "\(totalCoins)"
if ( coin > 0) {
totalCoins += coin
totalCoinLabel.text = String(format: "Total Coins: \(totalCoins)")
NSUserDefaults.standardUserDefaults().setInteger(totalCoins, forKey: "Total Coins")
}
func updateCoinTotal() {
coinLabel.text = String(coin)
totalCoinLabel.text = String(totalCoins)
totalCoins = NSUserDefaults.standardUserDefaults().integerForKey("Total Coins")
totalCoinLabel.text = "\(totalCoins)"
if (coin > 0) {
totalCoins += coin
totalCoinLabel.text = NSString(format: "%i", totalCoins) as String
NSUserDefaults.standardUserDefaults().setInteger(totalCoins, forKey: "Total Coins")
}
但是硬币Int总是等于零,所以totalCoins永远不会更新。
这是我用来收集硬币的代码:
func colledCoin() {
totalCoins += 1
coin += 1
totalCoinLabel.text = String(totalCoins)
coinLabel.text = String(coin)
NSUserDefaults.standardUserDefaults().setInteger(totalCoins, forKey: "Total Coins")
}
func updateCoinLabels() {
totalCoins = NSUserDefaults.standardUserDefaults().integerForKey("Total Coins")
totalCoinLabel.text = String(totalCoins)
}