Save bool in nsuserdefaults

when the music application starts 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]; } 

but he should be able to turn off the music by pressing the button, if he presses the button again, the music will 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"]; } } 

I think I did not understand this. Now it works in my first ViewController that I can turn music on and off, but when I switch to another viewController while playing music, then press the button again and again, the music does not stop and when I click it many times the music is played a second time and overlaps.

What else is wrong?

+6
source share
3 answers

No need to wrap it in NSNumber, there are several convenient methods for this:

To install BOOL, use:

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

To access it, use:

 [userDefaults boolForKey:@"yourKey"]; 

[EDIT YOUR ADDITIONAL QUESTION]

Not sure why you are using NSUserDefaults - what you are trying to achieve seems unnecessary to you? Here is 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; } 
+33
source

Insert the BOOL value into the NSNumber object and add it to NSUserDefault:

 NSUserDefaults *boolUserDefaults = [NSUserDefaults standardUserDefaults]; [boolUserDefaults setObject:[NSNumber numberWithBool:isquiet] forKey:@"stringKey"]; 

You can later get this value as a normal BOOL using the -boolForKey: function -boolForKey: in NSUserDefaults

+5
source

To save:

 [boolUserDefaults setObject:[NSNUmber numberWithBool:isQuiet] forKey:@"stringKey"]; 

When you read it, read it as NSNumber, and then do:

 BOOL savedIsQuiet = [theNumberYouSaved boolValue]; 
0
source

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


All Articles