2016-07-05 55 views
0

我正在嘗試保存收集到的硬幣,並將該數量添加到用戶收集的硬幣總量中(在SpriteKit中)。使用當前代碼,硬幣當前不保存,並且沒有任何內容被添加到總數中。我不確定爲什麼硬幣沒有保存,因爲我在代碼中看不到任何明顯的錯誤。任何幫助或解釋爲什麼這是不應該的方式應該會不勝感激。跟蹤收集的硬幣總數Swift 3

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

韋爾普這很煩人。我嘗試了一下修改代碼,每次嘗試查看是否存在NSUserfefault中存儲的值,但我什麼也沒找到。通過遊樂場檢查:https://gist.github.com/anonymous/0468c16c03fdbdf6717256d0a902a13d – KFDoom

+0

我現在要檢查! @KFDoom –

回答

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") 


} 

但硬幣詮釋總是等於零所以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) 
} 
+0

謝謝你的回答!我需要使用'totalCoinDefault.synchronize()'命令嗎? –

+0

你不需要使用它。 – Loanb222