我有一个设置视图,我为用户提供了更改设置的选项。
设置视图的table view
有2 UISwitches
。我需要帮助NSUserdefaults
方法来保存状态,以及如何编写代码来加载我的值。
到目前为止,这是我的代码
In `cellForRowAtIndexPath` method:
[cell.switchButton addTarget:self action:@selector(switchButtonTapped:) forControlEvents:UIControlEventValueChanged];
[[NSUserDefaults standardUserDefaults] setBool:TRUE forKey:@"myBool"];
BOOL hBool = [[ NSUserDefaults standardUserDefaults] boolForKey:@"myBool"];
NSLog(@"tag %i", tappedSwitch.tag);
if (cell.switchButton.tag == 0) {
[cell.switchButton setOn:hBool];
}
return cell;
}
- (void) switchButtonTapped: (id) sender {
tappedSwitch = (UISwitch *) sender;
switch (tappedSwitch.tag) {
case 0:
passcodeSwitchIsOn = tappedSwitch.isOn;
if (passcodeSwitchIsOn) {
GCPINViewController *PIN = [[GCPINViewController alloc]
initWithNibName:nil
bundle:nil
mode:GCPINViewControllerModeCreate];
PIN.messageText = @"Enter a passcode";
PIN.errorText = @"The passcodes do not match";
PIN.title = @"Set Passcode";
PIN.verifyBlock = ^(NSString *code) {
NSLog(@"setting code: %@", code);
code = saveString;
return YES;
};
[PIN presentFromViewController:self animated:YES];
[PIN release];
// method of saving
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
[defaults setBool:passcodeSwitchIsOn forKey:@"myBool"];
[defaults synchronize];
}
break;
case 1:
bluetoothSwitchIsOn = tappedSwitch.isOn;
if (bluetoothSwitchIsOn) {
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Bluetooth Switch" message:@"Bluetooth Switch is ON" delegate:self cancelButtonTitle:@"Okay" otherButtonTitles:nil, nil];
[alert show];
[alert release];
}
break;
default:
break;
}
[settingsTable reloadData];
}
答案 0 :(得分:3)
创建对用户默认值的引用:
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
设定值:
[defaults setBool:1 forKey:@"bluetooth"];
当蓝牙关闭时,您可以将其设置为0:
[defaults setBool:0 forKey:@"bluetooth"];
用户默认值由您选择的字符串标识。在这种情况下:@“bluetooth”。在您创建默认值并将其设置为其他值之前,默认值将为nil。
所以你可以说:
if (!bluetooth) // bluetooth is off
else // bluetooth is on
答案 1 :(得分:2)
这可用于处理您的问题。
IBOutlet UISwitch * swi_yourswitch;
@property(nonatomic,retain) UISwitch * swi_yourswitch;
<强>执行力度强>
@synthesise swi_yourswitch;
- (void) switchButtonTapped: (id) sender {
UISwitch * switchObj = (UISwitch*)sender;
if(switchObj == self.swi_yourswitch){
if (self.swi_yourswitch.on){
NSLog(@"On");
}
else{
NSLog(@"Off");
[self.swi_yourswitch setOn:0];
}
}
存储值
[[NSUserDefaults standardUserDefaults] setBool:TRUE forKey:@"mybool"];
[[NSUserDefaults standardUserDefaults] synchronize];
获取储值
[NSUserDefaults standardUserDefaults] valueForKey:@"mybool"]