有没有一种方法可以用 NSUserDefaults 存储 UISwitch 的状态?
如果状态为 ON,我想设置一些操作...
我可以这样做吗?
谢谢!
有没有一种方法可以用 NSUserDefaults 存储 UISwitch 的状态?
如果状态为 ON,我想设置一些操作...
我可以这样做吗?
谢谢!
hotpaw2 的答案很好,也可以很好地用于大分段控制(超过 2 个状态)。但是如果你只想存储 2 个状态,为什么不[setBool:forKey:]
这样使用
NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
[userDefaults setBool:switchState forKey:@"mySwitchValueKey"];
把它拿出来:
BOOL swichState = [userDefaults boolForKey:@"mySwitchValueKey"];
哪个imo,要简单得多,根本没有if else代码,没有字符串转换回来和for
保存:
- (void)mySwitchAction:(id)sender
{
if (sender == mySwitch) {
BOOL mySwitchValue = [ sender isOn ];
NSString *tmpString = mySwitchValue ? @"1" : @"-1" ;
NSUserDefaults *myNSUD = [NSUserDefaults standardUserDefaults];
[ myNSUD setObject:tmpString forKey: @"mySwitchValueKey" ];
[ myNSUD synchronize ];
// do other stuff/actions
}
}
从保存状态初始化:
NSUserDefaults *myNSUD = [NSUserDefaults standardUserDefaults];
NSString *tmpString = [ myNSUD stringForKey: @"mySwitchValueKey"];
BOOL mySwitchValue = NO; // or DEFAULT_VALUE
if (tmpString != nil) {
mySwitchValue = ( [ tmpString intValue ] == 1 );
}
[mySwitch setOn: mySwitchValue];