這應該將兩個UISwitch的值保存到NSUserDefaults,然後根據保存爲默認值的值設置加載開關。我一直在這個小時,但我似乎無法讓它工作。任何幫助將不勝感激。嘗試使用NSUserDefaults保存並設置UISwitch狀態
切換位於我用於設置的視圖中。只有兩個切換,所以我想使用NSUserDefaults。切換默認爲OFF。我想切換到開,並保存更改,以便根據切換值更改用戶體驗。然後,當用戶再次打開設置時,我希望它們顯示當前保存的狀態。
我認爲這個值正在保存,但是當我重新進入設置視圖時它沒有被應用到交換機上。
- (IBAction)setBeadVibratorBySwitchState:(id)sender
{
if (setBeadVibrator.selected == YES) {
NSUserDefaults *beadSettings = [NSUserDefaults standardUserDefaults];
[beadSettings setBool:NO forKey:@"beadSwitchStatus"];
[beadSettings synchronize];
}
if (setBeadVibrator.selected == NO) {
NSUserDefaults *beadSettings = [NSUserDefaults standardUserDefaults];
[beadSettings setBool:YES forKey:@"beadSwitchStatus"];
[beadSettings synchronize];
}
NSLog(@"Bead Executed");
}
- (IBAction)setDecadeVibratorBySwitchState:(id)sender
{
if (setDecadeVibrator.selected == YES) {
NSUserDefaults *decadeSettings = [NSUserDefaults standardUserDefaults];
[decadeSettings setBool:NO forKey:@"decadeSwitchStatus"];
[decadeSettings synchronize];
}
if (setDecadeVibrator.selected == NO){
NSUserDefaults *decadeSettings = [NSUserDefaults standardUserDefaults];
[decadeSettings setBool:YES forKey:@"decadeSwitchStatus"];
[decadeSettings synchronize];
}
NSLog(@"Decade Executed");
}
- (void)viewDidLoad
{
[super viewDidLoad];
setBeadVibrator.selected = [[NSUserDefaults standardUserDefaults] boolForKey:@"beadSwitchStatus"];
setDecadeVibrator.selected = [[NSUserDefaults standardUserDefaults] boolForKey:@"decadeSwitchStatus"];
}
您能否描述一下您使用此代碼的問題?當你運行你的代碼時,你預期發生的事情不會發生嗎? – dasblinkenlight 2012-07-30 02:13:32
已編輯。謝謝! – Sneagan 2012-07-30 02:52:39
您是否嘗試從'viewDidLoad'切換到'viewWillAppear'? – dasblinkenlight 2012-07-30 02:57:21