如何在NSUserDefault中使用UISwitch

时间:2014-05-15 04:12:05

标签: ios nsuserdefaults uiswitch

 defaults = [NSUserDefaults standardUserDefaults];
 NSLog(@"%@",[defaults objectForKey:@"firsttime"])

if([[defaults objectForKey:@"firsttime"]isEqualToString:@"YES"])
{
    UISwitch *onoff = (UISwitch *) sender;
    if(onoff.on)
    {
        NSLog(@"yes on1 facebookswitch");
        facebookSwitch.on = YES;
        [userDefault setValue:@"true" forKey:@"facebooknotify"];

        NSLog(@"on");
        if ([SLComposeViewController isAvailableForServiceType:SLServiceTypeFacebook]) {
            [validate alertCommonWithoutMessage:NSLocalizedString(@"val_message",nil) :NSLocalizedString(@"val_facebook_login",nil) :@"OK"];
            facebookSwitch.on = YES;
            NSLog(@"yes on2 facebookswitch");

        }
        else {
            NSLog(@"val_facebook_conf");
            [validate alertCommonWithoutMessage:NSLocalizedString(@"val_message",nil) :NSLocalizedString(@"val_facebook_conf",nil) :@"OK"];
            facebookSwitch.on = NO;
            [userDefault setValue:@"false" forKey:@"facebooknotify"];
            NSLog(@"yes off1 facebookswitch");

我使用这种方法,但是响应时间为空。

2 个答案:

答案 0 :(得分:0)

至于为何无效,最常见的问题是[userDefault synchronize]

此外,为什么不使用:

,而不是使用字符串布尔值
[userDefault setBool:YES forKey:@"facebooknotify"];

然后通过

访问
BOOL notified = [userDefault boolForKey:@"facebooknotify"];

答案 1 :(得分:0)

试试这段代码:

// add this code in your switch touch event
- (IBAction)YourSwitch:(UISwitch*)sender
{
    if (UISwitch.on)
    {
        NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
        [defaults setBool:true forKey:@"Sound"];
        [defaults synchronize];
    }
    else
    {
        NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
        [defaults setBool:false forKey:@"Sound"];
        [defaults synchronize];
    }
}

// add this code in your viewDidload .
BOOL isSound= [[NSUserDefaults standardUserDefaults] objectForKey:@"Sound"];

if (isSound){
    _ref_slider.on=TRUE;
} else {
    _ref_slider.on=FALSE;
}

我希望这段代码对你有用。