I have a UISwitch which is used to turn on or turn off a sound. The state is saved using NSUserDefaults. Works great. But if the app is started from the very first beginning after installing it, the BOOL value is 0 and the switch is OFF. Because no value has been saved earlier.
So default is OFF and you are able to turn it ON and next time it is still ON.
I would like it the other way round, so when installing the app the switch is ON by default and you are able to turn it OFF.
How do I solve that?
In
application:didFinishLaunchingWithOptions:, you check if a paritcular key is already set. Ifnilis returned, then you set it to the default value of your choice. Take a look at the snippet below for clarification.I recommend that you use
objectForKey:in yourifstatement as this makes the code easier and less error prone. The default value can be anything you like, of course.Objective-C
Swift 3