bool saving problem

做~自己de王妃 提交于 2019-12-11 23:41:00

问题


Edited

i've got a sound in my app which begins to play when the app is started. further I've got two method to play and stop the sound:

-(void)playBgMusic {

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


 -(void)stopMusic {

[theAudio stop];
[defaults setBool:YES forKey:@"isQuiet"]; }

Now I've got different viewControllers and in my mainView there's a button which stops/starts the music (depends on wheter music is playing or not).

So I've got:

-(IBAction)check {

isquiet = [defaults boolForKey:@"isQuiet"];

if (isquiet == YES) {

    [self playBgMusic];

    // Change button to indicate music is playing

} 

else {

    [self stopMusic];

    // Change the button to indicate music has stopped...
}

}

Now there's a problem. The sound plays when the app is started, after that I can press the button and the sound is stopped but then I cant start it again. I've put NSLogs in the code and saw that the BOOL is still NO after pressing the stopButton.

Where's my mistake?


回答1:


This is not an answer, strictly speaking, but hopefully it'll set you on the right track...

Add some logging (either via NSLog(...) or add logging breakpoints) to the NO and YES cases of the above code that outputs the value of isquiet. Then you can see which code paths are invoked when you press the button under different scenarios.




回答2:


You are on the right track, the only thing missing is actually saving the bool value back to NSUserDefaults when you start/stop playing, so everytime you click the button and read it, you get the correct value.

Give this a try and see if it helps:

-(IBAction)check 
{
    BOOL isQuiet = [userDefaults boolForKey:@"isQuiet"];
    if (isQuiet)
    {
        [self playBgMusic];
        // Change button to indicate music is playing
    } else {
        [self stopBgMusic];
        // Change the button to indicate music has stopped...
    }
}

Then in your playBgMusic method, add the following:

[userDefaults setBool:NO forKey:@"isQuiet"];

And in your spotBgMusic method, add the following:

[userDefaults setBool:YES forKey:@"isQuiet"];


来源:https://stackoverflow.com/questions/5588209/bool-saving-problem

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!