2015-11-09 26 views
0

我擁有它,所以當我的遊戲結束時,它切換到單獨的SKScene,它顯示新的高分。這裏是我的代碼:主題1:使用NSUserDefaults的EXC_BAD指令

func saveState() { 

    let defaults = NSUserDefaults.standardUserDefaults() 
    defaults.setInteger(highScore, forKey: "labelScore") //this line says "unexpectedly found nil while unwrapping an optional value 
    defaults.setInteger(stars, forKey: "SNOW") 
    NSUserDefaults.standardUserDefaults().synchronize() 
} 

什麼可能是零?我有這個函數中的所有東西的值。如果需要,將發佈更多代碼。

+0

高分可能是零。只需使用後衛let highscore = highscore else {return} –

回答

1

這意味着它可能保存錯誤開始。我建議使用常量來訪問用戶默認值,以避免這種情況發生。

編輯:

我最常做的是創建一個單獨的文件,該文件是一個全局常量文件作爲結構 在這個文件中的一部分,你可以定義常量,像這樣:

struct GlobalConstants { 
    static let defaultsHighScore = "labelScore" 
} 

然後,當我嘗試讀取默認值時,不是每次都輸入所有內容,我可以使用像這樣的常量:defaults.setInteger(highScore, forKey: GlobalConstants.defaultsHighScore)

+0

你能舉個例子說明你的意思嗎? –

+0

我會給這個鏡頭!非常感謝! –

+0

不客氣!另請注意,從iOS 8開始,Apple建議您在更新默認值後不再同步它們。如果你覺得這個對你有用,請投我的回答:) – pbush25