【发布时间】:2012-02-26 22:30:21
【问题描述】:
我几天来一直在尝试将UISwitch 状态保存在我的tableViewController 行上,但无济于事。我查看了各种 stackOverflow 问题和回复以及苹果文档,但在我的应用中似乎没有任何效果。
这是我的应用委托:
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
NSDictionary *appDefaults = [NSDictionary dictionaryWithObject:@"No" forKey:@"emailSwitch"];
[defaults registerDefaults:appDefaults];
[defaults synchronize];
}
我在 Settings.bundle 集中有 Root.plist,这似乎可以正常工作,并将开关结果保存在应用程序设置中,但不在 tableViewController 上。例如,如果我在设置中将其切换为“开启”,当我将对象添加到我的tableViewController 时,该开关就会“关闭”。
这里是tableViewController.h文件中的相关代码:
@property (nonatomic, getter=isOn) BOOL on;
- (void)toggleValue:(id)sender;
这里是tableViewController m文件中的相关代码:
- (void)viewWillAppear:(BOOL)animated
{
if ([[NSUserDefaults standardUserDefaults] boolForKey:@"emailSwitch"])
{
[emailSwitch setOn:YES animated:NO];
}
else
{
[emailSwitch setOn:NO animated:NO];
}
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = @"Cell";
customTableViewCell *cell = (customTableViewCell *)[tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[CustomTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
}
//Code regarding cell contents here
UISwitch *switchObj = [[UISwitch alloc] initWithFrame:CGRectZero];
[switchObj addTarget:self action:@selector(toggleValue:) forControlEvents:(UIControlEventValueChanged | UIControlEventTouchDragInside)];
cell.accessoryView = switchObj;
return cell;
}
-(void)toggleValue:(id)sender
{
[[NSUserDefaults standardUserDefaults] setBool:emailSwitch.on forKey:@"emailSwitch"];
[[NSUserDefaults standardUserDefaults] synchronize];
}
当您将对象添加到tableViewController 并将UISwitch 切换为“on”时,它不会保存“on”状态。我尝试了各种方法,但没有任何效果。如果有人能告诉我我做错了什么,我将不胜感激。提前感谢您提供的任何帮助。
【问题讨论】:
标签: ios xcode4.2 nsuserdefaults uiswitch