2015-10-05 28 views
0

我有一個UIPickerView可讓用戶更改國家設置。NSUserDefaults對象在執行委託方法後沒有進入

func pickerView(pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) { 
    let defaults = NSUserDefaults.standardUserDefaults() 
    defaults.setObject(countries[row], forKey: "SelectedCountry") 
    let test = defaults.stringForKey("SelectedCountry") 
    delegate?.countryChanged() 
} 

這個test變量得到正確的值。

然而,當委託方法countryChanged叫我得到一個錯誤:

fatal error: unexpectedly found nil while unwrapping an Optional value 

這是代碼:

func countryChanged() { 
    let defaults = NSUserDefaults.standardUserDefaults() 
    countryLabel.text = defaults.stringForKey("SelectedCountry") 
} 

的價值怎麼能是零?這是調用委託方法之前的正確國家,並且沒有修改此值的代碼。

+0

能否請您分享您的sameple項目? – Max

+0

您應該確保'countries [row]'實際上包含一個'String'。 –

+0

FUNC countryChanged(){ 讓默認= NSUserDefaults.standardUserDefaults() 如果讓文本= defaults.stringForKey( 「SELECTEDCOUNTRY」){ countryLabel?的.text =文本 } } – Lukas

回答

-1

你必須堅持你的修改NSUserDefaults的:

func pickerView(pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) { 
    let defaults = NSUserDefaults.standardUserDefaults() 
    defaults.setObject(countries[row], forKey: "SelectedCountry") 
    defaults.synchronize() // must call synchronize here to save your modifications 
    let test = defaults.stringForKey("SelectedCountry") 
    delegate?.countryChanged() 
} 
+1

'不需要synchronize'並且不有助於反映應用程序內的變化。 –

相關問題