Problem saving bool

Edited

I have a sound in my application that starts playing when the application starts. Further, I have two ways 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 have different viewControllers, and in my mainView there is a button that stops / starts the music (it depends on which music is playing or not).

So, I have a:

 -(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 is a problem. The sound is played when the application starts, after which I can press the button and the sound is stopped, but then I can not start it again. I put NSLogs in code and saw that BOOL is still NO after clicking the stopButton button.

Where is my mistake?

0
source share
2 answers

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

Add some entries (either via NSLog(...) , or add checkpoints) in cases of NO and YES of the above code, which displays the value isquiet . Then you can see which code paths are called up when the button is clicked in different scripts.

0
source

You're on the right track, the only thing missing is actually saving the bool value back to NSUserDefaults when starting / stopping the game, so every time you click the button and read it, you get the correct value.

Try and see if this 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"]; 
0
source

Source: https://habr.com/ru/post/885458/


All Articles