Ios 保存UISwitch结果和NSUserDefaults

Ios 保存UISwitch结果和NSUserDefaults,ios,xcode4.2,nsuserdefaults,uiswitch,Ios,Xcode4.2,Nsuserdefaults,Uiswitch,几天来,我一直试图在我的tableViewController行上保存UISwitch状态,但没有成功。我查看了各种stackOverflow问题和回答以及苹果的文档,但我的应用程序似乎没有任何效果 这是我的应用程序代理: - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions { NSUserDefaults *defa

几天来,我一直试图在我的
tableViewController
行上保存
UISwitch
状态,但没有成功。我查看了各种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,这似乎起作用了,并将切换结果保存在app Settings中,而不是保存在
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
切换为“开”时,它不会保存“开”状态。我尝试过各种方法,但都不管用。如果有人能告诉我我做错了什么,我会非常感激。提前感谢您提供的任何帮助。

如果我正确理解您的问题,您的toggleValue方法应该如下所示:

-(void)toggleValue:(UISwitch*)sw
{
  [[NSUserDefaults standardUserDefaults] setBool:sw.on forKey:@"emailSwitch"];

  [[NSUserDefaults standardUserDefaults] synchronize];
}

谢谢你回答这个问题,但正如你所看到的,这是10个月前提出的——我决定放弃不起作用的东西,重新开始。