2011-06-14 143 views
0

我有一個相當簡單的iPhone應用程序,我正在做。但是,我無法讓我的NSUserDefaults永久保存。寫入和檢索數據不是問題 - 我可以保存數據(在我的情況下是一個字符串),並在命令中檢索它,即使在切換視圖,關閉/打開應用程序等之後,數據也只是被檢索到精細。看起來好像字符串已正確保存到密鑰中。但是,當我從多任務托盤中退出應用程序並重新啓動它時,設置不再保存,應用程序就像第一次啓動一樣。我是一個新手程序員,所以這可能只是我的一個愚蠢的錯誤。NSUserDefaults不會永久保存

這裏的儲蓄是什麼樣子:

if (optionsSoundBox.center.x >= 240) 
    { 
     [UIView beginAnimations:nil context:nil]; 
     [UIView setAnimationDuration:.2]; 
     self.soundOnLabel.alpha = 1; 
     self.soundOffLabel.alpha = 0; 
     [UIView commitAnimations]; 

     NSUserDefaults *soundOptions = [NSUserDefaults standardUserDefaults]; 
     [soundOptions setObject:@"SoundsON" forKey:@"SoundKey"]; 
     [soundOptions synchronize]; 
    } 

    if (optionsSoundBox.center.x < 240) 
    { 
     [UIView beginAnimations:nil context:nil]; 
     [UIView setAnimationDuration:.2]; 
     self.soundOnLabel.alpha = 0; 
     self.soundOffLabel.alpha = 1; 
     [UIView commitAnimations]; 

     NSUserDefaults *soundOptions = [NSUserDefaults standardUserDefaults]; 
     [soundOptions setObject:@"SoundsOFF" forKey:@"SoundKey"]; 
     [soundOptions synchronize]; 
    } 

我找回在viewDidLoad中的字符串,所以這將是準備在啓動時是這樣的:

NSUserDefaults *soundOptions = [NSUserDefaults standardUserDefaults]; 
    NSString *savedSoundSettings = [soundOptions stringForKey:@"SoundKey"]; 

    if (savedSoundSettings == @"SoundsON") 
    { 
     [optionsSoundBox setCenter:CGPointMake(280, optionsSoundBox.center.y)]; 
    } 

    if (savedSoundSettings == @"SoundsOFF") 
    { 
     [optionsSoundBox setCenter:CGPointMake(200, optionsSoundBox.center.y)]; 
    } 

我真的很感激任何幫助,您可以給

回答

0

您應該使用[savedSoundSettings isEqualToString:@"SoundsON"],而不是使用double equals運算符。 (==)。

除此之外,它可能是你在viewDidLoad裏面運行這個代碼的事實。嘗試在viewWillAppear之內運行它。

最後,我建議使用camelcase名稱作爲設置鍵,所以長時間輸入會更容易。 (想想soundsOn而不是SoundsON。)

0

您不應該將字符串與==進行比較。比較字符串的正確方法是通過isEqualToString:。所以,你如果在獲取用戶默認語句應該是這樣的:

if ([savedSoundSettings isEqualToString:@"SoundsON"]) 
{ 
    .... 
} 

編輯:此外,在概念上,你正在檢查是一個單一的狀態變量是否開啓或關閉。所以你最好應該使用類似[NSUserDefaults setBool:forKey:][NSUserDefaults boolForKey:]

1

又因爲你得到stringForKey:代替objectForKey:

也許它會如果你只是使用[[NSUserDefaults standardUserDefaults] setBool: YES forKey: @"SoundsON"];,然後檢查是否boolForKey: @"SoundsON"是真心對你會更容易。