在保存NSUserDefaults的布尔 [英] save bool in nsuserdefaults

查看:116
本文介绍了在保存NSUserDefaults的布尔的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的应用程序启动音乐播放:

when my app starts music is playing:

-(void)playBgMusic {

NSString *path = [[NSBundle mainBundle] pathForResource:@"bgmusic" ofType:@"aif"];
theAudio = [[AVAudioPlayer alloc] initWithContentsOfURL:[NSURL fileURLWithPath:path] error:NULL];
theAudio.delegate = self;
[theAudio play];    }

但他应该能够通过pressing一个按钮,把音乐关闭,如果他presses按钮再次音乐应该再次打开。我有:

but he should be able to turn the music off by pressing a button if he presses the button again the music should turn on again. i have:

-(IBAction)check {


if (isquiet == NO) {

    [theAudio stop];

    isquiet = YES;

     defaults = [NSUserDefaults standardUserDefaults];
    [defaults setBool:YES forKey:@"stringKey"];


}

else {

    [self playBgMusic];

    isquiet = NO;

    defaults = [NSUserDefaults standardUserDefaults];
    [defaults setBool:NO forKey:@"stringKey"]; } }

我觉得我没有得到它。现在,它的作品在我的第一的ViewController,我可以把音乐和关闭,但是当我去到另一个的viewController而正在播放的音乐,然后再回到和preSS按钮,音乐不会停止,当我preSS了很多次的音乐播放,第二次和重复。

I think I didn't get it. Now it works in my first ViewController that I can turn the music on and off but when I go to another viewController while the music is playing, then back again and press the button, the music doesn't stop and when i press it many times the music is played a second time and overlaps.

什么是错了还是?

推荐答案

没有必要把它包在一个NSNumber,这是你的一些方便的方法:

No need to wrap it in an NSNumber, there are some convenience methods for this:

要设置BOOL,使用:

To set a BOOL, use:

[userDefaults setBool:YESorNO forKey:@"yourKey"];

要访问它,使用:

[userDefaults boolForKey:@"yourKey"];

不知道为什么你正在使用NSUserDefaults的 - 你要实现的目标似乎没有必要呢?下面是我会为一个按钮,就可以开始做/停止音乐:

Not sure why you are using NSUserDefaults - it seems unnecessary for what you are trying to achieve? Here's what I would do for a button that can start/stop music:

-(IBAction)check 
{
    if (isQuiet)
    {
        // Play music
        // Change the button to indicate it is playing...
    } else 
    {
        // Stop music
        // Change the button to indicate it has stopped...
    }
    // Set your isQuiet to be the opposite of what it was when the button was clicked
    isQuiet = !isQuiet;
}

这篇关于在保存NSUserDefaults的布尔的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆